dom4j解析xml

        前言:对于不同类型的需求,解析为不同的类型,比如Map或者List,而不是对于任何格式通用的解析方法。 该笔记的出发

点是:和其它开发人员对接数据,对方提供格式一定的xml数据,我负责解析成JAVA里Map类型的数据。

        第三方jar包:

1、xml文本

<?xml version="1.0" encoding="UTF-8"?>
<root>
	<code>1</code>
	<info>返回值描述</info>
	<data>
		<entity>
			<id>ID标识</id>
			<attribute1>属性1</attribute1>
			<attribute2>属性2</attribute2>
			<attribute3>属性3</attribute3>
			<attribute4>属性4</attribute4>			
		</entity>
	</data>
</root>

2、代码验证

public void parseXML() throws Exception {
    String xmlStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
            "<root>\n" +
            "\t<code>1</code>\n" +
            "\t<info>返回值描述</info>\n" +
            "\t<data>\n" +
            "\t\t<entity>\n" +
            "\t\t\t<id>ID标识</id>\n" +
            "\t\t\t<attribute1>属性1</attribute1>\n" +
            "\t\t\t<attribute2>属性2</attribute2>\n" +
            "\t\t\t<attribute3>属性3</attribute3>\n" +
            "\t\t\t<attribute4>属性4</attribute4>\t\t\t\n" +
            "\t\t</entity>\n" +
            "\t</data>\n" +
            "</root>";
    Map<String, Object> res = new HashMap<String, Object>();
    Document doc = reader.read(new ByteArrayInputStream(xmlStr.getBytes("UTF-8")));
    Element root = doc.getRootElement();  //获取根节点,忽略xml文件中的第一行
    res.put("code", root.element("code").getText());  //获取code节点
    res.put("info", root.element("info").getText());  //获取info节点
    Element data = root.element("data");              //获取data节点
    List<Map<String, String>> tmpList = new ArrayList<Map<String, String>>();
    List list = data.elements("entity");   //获取data节点下的entity节点,一个data下可以有多个entity
    Iterator iterator = list.iterator();
    while (iterator.hasNext()) {
        Element ele = (Element) iterator.next();
        Map<String, String> map = new HashMap<String, String>();
        Iterator<Element> eItor = ele.elementIterator();
        while (eItor.hasNext()) {  //对其中的一个entity遍历
            Element element = eItor.next();
            map.put(element.getName(), element.getText());
        }
        tmpList.add(map);
    }
    res.put("data", tmpList);
    System.out.println(res);
}

3、解析结果

{code=1, data=[{attribute4=属性4, attribute1=属性1, attribute3=属性3, id=ID标识, attribute2=属性2}], info=返回值描述}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值