您的位置:首页 > 编程语言 > Java开发

java使用dom4j解析xml

2014-08-18 23:57 447 查看
目标:将指定XML进行解析,以键=值的方式返回指定节点下的数据

所需要的jar包:dom4j1.6.1.jar、jaxen-1.1.jar

package cn.code;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class Dom4JParseXml {
public static void main(String[] args) {
SAXReader reader = new SAXReader();
File file = new File("in.xml");
try {
Document doc = reader.read(file);
Element root = doc.getRootElement();
String nodePath = "/business/list/item";
System.out.println(bar(root, nodePath));
} catch (DocumentException e) {
e.printStackTrace();
}
}

// 遍历root 直到它的下一个节点为Node
public static String bar(Element root, String nodePath)
throws DocumentException {
Iterator i = root.elementIterator();
Element element = null;
while (i.hasNext()) {
element = (Element) i.next();
if (element.elementIterator().hasNext()) {
return bar(element, nodePath);
} else {
return barNode(element, nodePath);
}
}
return null;
}

// 遍历element下的Node
public static String barNode(Node node, String nodePath) {
StringBuffer buf = new StringBuffer();
try {
Document document = DocumentHelper.parseText(node.getStringValue());
List list1 = document.selectNodes(nodePath);
for (Object object : list1) {
Element n = (Element) object;
List i201_ = n.elements();
for (Object object2 : i201_) {
Node i_node = (Node) object2;
buf.append(i_node.getName() + "="
+ i_node.getStringValue().trim());
}
}
} catch (Exception e) {
System.out.println("node.getStringValue() parseText Exception");
}
return buf.toString();
}
}


View Code
上面是完整的代码。

注意以上的XML中,element arg0下面的数据是通过<![CDATA[..]]>包围的,<![CDATA[..]]>中的文本解释器是不会执行的(会被解析器忽略),那么从这可以知道arg0是一个节点的元素(element),而<![CDATA[..]]>里面的内容只是个纯文本.所以在bar这个方法中用到了迭代,主要是将纯文本拿到。

第二,由纯文本的结构可知,该文本是一个document,故在barNode这个方法里,首先将这个文本解析成一个document.然后调用document.selectNodes("");方法得到一个Node的集合,再进行遍历. 其中document还有document.selectSingleNode("")方法,这个方法是直接得到一个Node节点.

参考资料:http://dom4j.sourceforge.net/dom4j-1.6.1/guide.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: