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
	}

}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值