1. 程式人生 > >dom4j解析XML案例

dom4j解析XML案例

    有時候第三方會提供給你XML檔案,然後儲存你所需的相關資訊。那就需要解析XML,然後轉為json字串是比較常規的做法。

    利用dom4j的XPATH語法能夠容易獲取你想要的資料,瞭解XPATH:http://www.w3school.com.cn/xpath/xpath_syntax.asp

 

    通過複製你的XML放入json線上解析格式中,如下圖,方便解析資料:

    

 

 

   前奏:引入dom4j的jar包

   第一步:讀XML檔案

SAXReader saxReader = new SAXReader();
Document doc = saxReader.read(xmlPath);

 第二步:獲取SoundRecording裡面的陣列

List<Element> resourceList = doc.selectNodes("//ResourceList/SoundRecording");

第三部:遍歷陣列

Iterator<Element> resourceListIt = resourceList.iterator();

while (resourceListIt.hasNext()) {

    Element soundRecording = resourceListIt.next();
}

裡面如果還有陣列例如SoundRecordingDetailsByTerritory/Title

在第三部的遍歷的內層繼續遍歷

while (resourceListIt.hasNext()) {

    Element soundRecording = resourceListIt.next();
    
	List<Element> titleList = soundRecording.selectNodes("SoundRecordingDetailsByTerritory/Title");

    Iterator<Element> titleListIt = titleList .iterator();

    while (titleListIt.hasNext()) {


        Element title= titleListIt.next();

    }

}

第四部:獲取TitleText的值

Node titleNode= displayArtist.selectSingleNode("TitleText");
if (titleNode!= null) {
	String  titleValue= titleNode.getText());
	}

 

第五步:對於不是陣列的型別可以簡單使用XPATH語法獲取,比如獲取SoundRecordingDetailsByTerritory/TerritoryCode

 

while (resourceListIt.hasNext()) {

    Element soundRecording = resourceListIt.next();
	Node territoryCodeNode= soundRecording .selectSingleNode("SoundRecordingDetailsByTerritory/TerritoryCode");
    
    if (territoryCodeNode!= null) {
	String  territoryCodeValue= territoryCodeNode.getText());   // Worldwide
	}

}