XmlJson.java
2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.tianbo.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.Attribute;
import org.dom4j.Element;
import java.util.List;
import static org.apache.commons.lang.StringUtils.isEmpty;
/**
* @author shenhl
* <p>
* 2022/1/11/14:39
*/
public class XmlJson {
/**
* xml转json
* @param element
* @param json
*/
public static void dom4j2Json(Element element, JSONObject json){
//如果是属性
for(Object o:element.attributes()){
Attribute attr=(Attribute)o;
if(!isEmpty(attr.getValue())){
json.put("@"+attr.getName(), attr.getValue());
}
}
List<Element> chdEl=element.elements();
if(chdEl.isEmpty()&&!isEmpty(element.getText())){//如果没有子元素,只有一个值
json.put(element.getName(), element.getText());
}
for(Element e:chdEl){//有子元素
if(!e.elements().isEmpty()){//子元素也有子元素
JSONObject chdjson=new JSONObject();
dom4j2Json(e,chdjson);
Object o=json.get(e.getName());
if(o!=null){
JSONArray jsona=null;
if(o instanceof JSONObject){//如果此元素已存在,则转为jsonArray
JSONObject jsono=(JSONObject)o;
json.remove(e.getName());
jsona=new JSONArray();
jsona.add(jsono);
jsona.add(chdjson);
}
if(o instanceof JSONArray){
jsona=(JSONArray)o;
jsona.add(chdjson);
}
json.put(e.getName(), jsona);
}else{
if(!chdjson.isEmpty()){
json.put(e.getName(), chdjson);
}
}
}else{//子元素没有子元素
for(Object o:element.attributes()){
Attribute attr=(Attribute)o;
if(!isEmpty(attr.getValue())){
json.put("@"+attr.getName(), attr.getValue());
}
}
if(!e.getText().isEmpty()){
json.put(e.getName(), e.getText());
}
}
}
}
}