zoukankan      html  css  js  c++  java
  • dom4j解析xml

    最近项目中有用到解析xml的功能,之前也没接触过相关的信息,查点资料,做了个简单的解析程序,用到的dom4j,代码:

    public class XmlReader {

    /**
    * @description 将xml字符串转换成map
    * @param xml
    * @return Map
    */

    public static Map<String, String> readStringXmlOut(String xml) {
    Map<String, String> map = new HashMap<String, String>();
    Document doc = null;
    try {
    doc = DocumentHelper.parseText(xml); // 将字符串转为XML
    Element rootElt = doc.getRootElement(); // 获取根节点
    map.put(rootElt.getName(), rootElt.getName()); //插入根节点的值
    Iterator iter = rootElt.elementIterator(); // 获取根节点下的子节点(head、body)
    i = 0;  //重置序号
    map.putAll(getMap(iter, rootElt));
    } catch (DocumentException e) {
    e.printStackTrace();
    } catch (Exception e) {
    e.printStackTrace();
    }
    return map;
    }

    /**

    *由于项目中的xml有许多的层级相同标签且标签值相同的,也没想到什么好的办法去存放,只得在每个标签后面递加一个序号

    *如:<rd><PayAccNo>123</PayAccNo><rd><rd><PayAccNo>456</PayAccNo><rd><rd><PayAccNo>123</PayAccNo><rd>就会存放成map.put(PayAccNo0,123);map.put(PayAccNo1,456);map.put(PayAccNo2,123);

    */

    private static int i = 0; 

    public static Map<String, String> getMap(Iterator it, Element itemEle) {
    Map<String, String> map = new HashMap<String, String>();
    while (it.hasNext()) {
    Element ele = (Element) it.next();
    String key = ele.getName();
    String val = itemEle.elementTextTrim(ele.getName());
    if(ele.hasContent()){ //如果当前标签下存在子标签,递归调用解析
    map.putAll(getMap(ele.elementIterator(), ele));
    if(key.equals("rd")) i++;  //每解析完一个rd标签,序号加1
    }
    map.put(key + i, val);
    }
    return map;
    }
    }

  • 相关阅读:
    centos7 yum错误相关
    centos7 jenkins
    vim 常用命令
    Effective STL(第7条)
    【hihoCoder】1049.后序遍历
    C++ 单元测试 Cpputest
    【hihoCoder】1041. 国庆出游
    LeetCode(43. Multiply Strings)
    【LeetCode】16. 4Sum
    【LeetCode】1. Two Sum
  • 原文地址:https://www.cnblogs.com/eric-fang/p/4134446.html
Copyright © 2011-2022 走看看