使用Dom4J解析xml文件

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")



最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容