dom4j 解析字符串成树形结构

 

引入maven依赖:

<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.6.1</version>
</dependency>

 

public Map<String, Object> transferXml(Map<String, Object> result) {
        String content = String.valueOf(result.get("ltc_content"));
        Map<String, Object> data = new HashMap<>();
        Document document = null;
        try {
            document = DocumentHelper.parseText(content);
            Element root = document.getRootElement();
            data = recursiveXml(root);
            result.put("success", true);
            result.put("msg", "处理成功");
            result.put("data", data);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("msg", "xml格式错误");
        }
        return result;
    }

public Map<String, Object> recursiveXml(Element element) throws Exception {
        Map<String, Object> result = new HashMap<>();
        String textTrim = element.getTextTrim();
        result.put("text", textTrim);
        //处理属性
        Map<String, Object> attribute = new HashMap<>();
        List<Attribute> attributeList = element.attributes();
        for (Attribute attr : attributeList) {
            attribute.put(attr.getName(), attr.getValue());
        }
        result.put("attribute", attribute);
        //标签名
        result.put("label", element.getName());
        //子节点
        List<Map<String, Object>> childrenList = new ArrayList<>();
        List<Element> elementList = element.elements();
        for (Element ele : elementList) {
            Map<String, Object> child = recursiveXml(ele);
            childrenList.add(child);
        }
        result.put("children", childrenList);
        return result;
    }

  

content为xml字符串数据。

posted @ 2019-05-26 22:28  护花使者  Views(415)  Comments(0Edit  收藏  举报