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
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_42245930/article/details/85008747