JAVA实现XML格式数据转JSONObject

 

xml:

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

 

工具类

 XmlUtil.java

import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.*;

/**
 * xml数据转成json
 *
 * @author*/
public class XmlUtil {


    /**
     * 将所有xml数据转成json
     *
     * @param outputXml 要解析的xml数据
     * @return
     * @throws Exception
     */
    public static JSONObject xmlToJson(String outputXml) throws Exception {
        Document document = DocumentHelper.parseText(outputXml);
        Element root = document.getRootElement();
        // 遍历所有子节点
        return elementJson(root);
    }


    /**
     * xml节点转成JsonObject
     *
     * @param node
     * @return
     */
    public static JSONObject elementJson(Element node) {
        JSONObject result = new JSONObject();
        List<Attribute> listAttr = node.attributes();
        for (Attribute attr : listAttr) {
            result.put(attr.getName(), attr.getValue());
        }
        List<Element> listElement = node.elements();
        if (!listElement.isEmpty()) {
            for (Element e : listElement) {
                if (e.attributes().isEmpty() && e.elements().isEmpty()) {
                    result.put(e.getName(), e.getTextTrim());
                } else {
                    if (!result.containsKey(e.getName())) {
                        result.put(e.getName(), new JSONArray());
                    }
                    ((JSONArray) result.get(e.getName())).add(elementJson(e));
                }
            }
        }
        return result;
    }


}

 

使用

 public static void main(String[] args) throws Exception {
        String str="<?xml version=\"1.0\" encoding=\"utf-8\"?><root><Header><resultCode>0</resultCode></Header><Body><Desc>你好</Desc></Body></root>";
        System.out.println(XmlUtil.xmlToJson(str));
    }

 

结果  获取的是去掉根节点后的数据

{"Header":[{"resultCode":"0"}],"Body":[{"Desc":"你好"}]}

 

 

 

JAVA实现map集合转Xml格式,参考:https://www.cnblogs.com/pxblog/p/14006009.html

 

posted @ 2023-02-20 15:03  yvioo  阅读(951)  评论(0编辑  收藏  举报