dom4j是用來解析xml文件的java框架,簡單易用
1 加載xml文件
dom4j使用1.6.1,這也是目前使用最多的版本
<?xml version="1.0" encoding="UTF-8"?>
<hello color="red">
<head>
這是head部分
</head>
<world>
<body>
這是body部分
</body>
<test>
這是test部分
</test>
</world>
</hello>
package learndom4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
public class LearnDom {
public static void main(String[] args) {
SAXReader reader = new SAXReader();
try {
Document document = reader.read("learndom4j/hello.xml");
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
2 通過Document對象操作xml
首先是獲取xml當中的內(nèi)容,內(nèi)容可以分為四種類型:node、element、attribute、value
以上面的xml文件為例
獲取根節(jié)點
Element element = document.getRootElement()
獲取指定節(jié)點
List<Element> list = document.selectNodes("/world/body")
獲取節(jié)點的子節(jié)點
Element subroot = root.element("節(jié)點名") // 獲取節(jié)點名的第一個子節(jié)點
List subroots = root.elements("節(jié)點名") // 獲取節(jié)點名的所有子節(jié)點
List subroots = root.elements() // 獲取所有子節(jié)點
添加子節(jié)點
root.addElement("name")
獲取節(jié)點屬性 attribute
String res = root.attributeValue("color");
##### 獲取節(jié)點的內(nèi)容 value
root.getText();
修改節(jié)點的內(nèi)容
element.setText("value")