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
-----------------------有任何问题可以在评论区评论,也可以私信我,我看到的话会进行回复,欢迎大家指教------------------------
(蓝奏云官网有些地址失效了,需要把请求地址lanzous改成lanzoux才可以)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了