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 @   yvioo  阅读(1339)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示