xml转map json

 

xml转map json

<!--xml--> <dependency> <groupId>org.dom4j</groupId> <artifactId>dom4j</artifactId> <version>2.1.1</version> </dependency> <!--json--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> </dependency>

package com.yw.test.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: xml 转map
 * @author: YW
 * @time: 2020/10/12 13:09
 */
public class XmlToMapUtils {

    private static final Logger logger = LoggerFactory.getLogger(XmlToMapUtils.class);
    /**
     * @description: xml格式字符串转换为map
     * @author: YW
     * @time: 2020/10/12 13:16
     */
    public static Map<String, Object> multilayerXmlToMap(String xml) {
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(xml);
        } catch (DocumentException e) {
            logger.error("xml字符串解析,失败 --> {}", e);
        }
        Map<String, Object> map = new HashMap<>();
        if (null == doc) {
            return map;
        }
        // 获取根元素
        Element rootElement = doc.getRootElement();
        // 获取根节点下单元素
        recursionXmlToMap(rootElement, map);
        return map;
    }

    /**
     * @description: 多层 递归调用   element 节点元素  outmap 用于存储xml数据的map
     * @author: YW
     * @time: 2020/10/12 13:14
     */
    @SuppressWarnings("unchecked")
    private static void recursionXmlToMap(Element element, Map<String, Object> outmap) {
        // 得到根元素下的子元素列表
        List<Element> list = element.elements();
        int size = list.size();
        if (size == 0) {
            // 如果没有子元素,则将其存储进map中
            outmap.put(element.getName(), element.getTextTrim());
        } else {
            // innermap用于存储子元素的属性名和属性值
            Map<String, Object> innermap = new HashMap<>();
            // 遍历子元素
            list.forEach(childElement -> recursionXmlToMap(childElement, innermap));
            outmap.put(element.getName(), innermap);
        }
    }


    public static void main(String[] args) {
        String s3="<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" +
                "<note>\n" +
                "<to>George</to>\n" +
                "<from>John</from>\n" +
                "<heading>Reminder</heading>\n" +
                "<body>Don't forget the meeting!</body>\n" +
                "</note>";
 
        Map<String, Object> map = multilayerXmlToMap(s3);
        String s = JSON.toJSONString(map, SerializerFeature.WriteMapNullValue);
        System.out.println(s);
    }
}
  

  

posted @ 2020-10-13 11:05  愿无违  阅读(176)  评论(0编辑  收藏  举报