[工具]Java xml 转 Json
依赖
<!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.37</version>
</dependency>
代码
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
@Slf4j
public class WTool_Xml {
public static JSONObject xmlToJson(String xml) {
// JSONObject entries = WTool.xmlToJson(xml);
// System.out.println(entries);
Document document = XmlUtil.parseXml(xml);
// String nodeName = document.getNodeName();
// String textContent = document.getTextContent();
NodeList childNodes = document.getChildNodes();
JSONObject obj = JSONUtil.createObj();
digui(obj, childNodes);
return obj;
}
public static JSONObject digui(JSONObject j节点Json, NodeList childNodes){
if(childNodes == null || childNodes.getLength() == 0){
return null;
}
// WTool_Xml_Entity j节点Json = WTool_Xml_Entity.builder().build();
// JSONObject j节点Json = JSONUtil.createObj();
int length = childNodes.getLength();
for (int i = 0; i < length; i++) {
Node item = childNodes.item(i);
// WTool_Xml_Entity z子节点Json = WTool_Xml_Entity.builder().build();
JSONObject z子节点Json = JSONUtil.createObj();
String j节点名称 = item.getNodeName();
if(j节点名称.equals("#text")){
continue;
}
// System.out.println("====================" + j节点名称 + "========================");
//内容
String textContent = item.getTextContent();
if(!StrUtil.isBlank(textContent)){
z子节点Json.set("#text", textContent);
// z子节点Json.setJ节点内容(textContent);
// System.out.println("内容:" + textContent);
}
//属性
NamedNodeMap attributes = item.getAttributes();
if(attributes != null && attributes.getLength() > 0){
JSONObject s属性Json = JSONUtil.createObj();
// JSONObject j节点属性Json = z子节点Json.getJ节点属性Json();
for (int j = 0; j < attributes.getLength(); j++) {
Node attr = attributes.item(j);
// System.out.println("属性:" + attr.getNodeName() + "=" + attr.getNodeValue());
s属性Json.set(attr.getNodeName(), attr.getNodeValue());
// z子节点Json.set(attr.getNodeName(), attr.getNodeValue());
// j节点属性Json.set(attr.getNodeName(), attr.getNodeValue());
}
z子节点Json.set("#属性", s属性Json);
}
//子集
NodeList childNodes1 = item.getChildNodes();
digui(z子节点Json, childNodes1);
// z子节点Json.set("#子集合", z子集合);
if (j节点Json.containsKey(j节点名称)) {
//变为集合
Object s上一个相同的节点 = j节点Json.get(j节点名称);
if(s上一个相同的节点 instanceof JSONArray){
((JSONArray) s上一个相同的节点).add(z子节点Json);
}else{
JSONArray x相同节点Json集合 = new JSONArray();
x相同节点Json集合.add(s上一个相同的节点);
x相同节点Json集合.add(z子节点Json);
j节点Json.set(j节点名称, x相同节点Json集合);
}
}else{
j节点Json.set(j节点名称, z子节点Json);
}
}
return j节点Json;
}
}