xml解析 dom4j使用介绍
- 2016-03-21 21:45:00
- admin
- 原创 1660
一、xml基础
xml(Extensible Markup Language)是一种可扩展标记语言,主要由以下部分构成:
头部:用于申明版本和编码等,<?xml version="1.0" encoding="UTF-8"?>
注释:可以输入任意字符, <!-- your comments -->
标记:即真正的内容。
CDATA:内容不被解析,一般用于放置一些特殊文本。
实体:用于申明特殊字符,或者给字符串取名。
二、dom4j的mvn配置(xml的解析库)
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
三、xpath的mvn配置(xml的查询库)
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
四、代码示例
代码下载:XmlDemo.java
工程文件:xml.rar
import java.io.*;
import java.util.*;
import org.dom4j.*;
import org.dom4j.io.*;
public class XmlDemo {
private static Route route = new Route();
private static Document loadXML(String filename) {
try {
SAXReader domReader = new SAXReader();
InputStream input = XmlDemo.class.getResourceAsStream(filename);
return domReader.read(input);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static void getRoute(Document doc) {
Element root = doc.getRootElement();
Element routeElem = root.element("route");
Element defElem = routeElem.element("default");
route.addDefault(defElem.getText());
Element items = routeElem.element("items");
List<Element> list = items.elements("item");
for (Element elem: list) {
route.addItem(elem.getText());
}
}
private static void selectElement(Document doc) {
List<Element> elems = doc.getRootElement()
.element("route")
.element("items")
.elements("item");
for (Element elemLocal: elems) {
System.out.println(elemLocal.getPath());
System.out.println(elemLocal.getName());
if (elemLocal.isTextOnly())
System.out.println(elemLocal.getText());
}
}
private static void iteratorXML(Document doc) {
Iterator iter = doc.getRootElement().elementIterator();
while (iter.hasNext())
System.out.println(((Element)iter.next()).getPath());
}
private static void xpathSample(Document doc) {
// detailed path
List<Element> list = doc.selectNodes("/config/route/items/item");
for(Element elem: list) {
System.out.println(elem.getText());
}
// any path
list = doc.selectNodes("//item");
for(Element elem: list) {
System.out.println(elem.getText());
}
}
public static void main(String[] args) {
Document doc = loadXML("/conf.xml");
getRoute(doc);
selectElement(doc);
iteratorXML(doc);
xpathSample(doc);
}
}
五、输出结果
/config/route/items/item
item
12001|1001|rules|12345678|rules.ser
/config/route/items/item
item
12001|1002|rules|12345678|rules.ser
/config/route
12001|1001|rules|12345678|rules.ser
12001|1002|rules|12345678|rules.ser
12001|1001|rules|12345678|rules.ser
12001|1002|rules|12345678|rules.ser