作者:中国有程序猿 | 来源:互联网 | 2023-10-12 20:43
?
?
?
?xml文件如下:
001
st001
0001
xue
bo
001
st001
0001
xue
bo
?用上一篇文章中的工具转换后,再转成json的结构如下:
?
{
"classs": [
{
"id": {
"id": "001"
},
"student": {
"id": {
"id": "0001"
},
"name": {
"last": {
"last": "bo"
},
"first": {
"first": "xue"
}
}
},
"name": {
"name": "st001"
}
},
{
"id": {
"id": "001"
},
"student": {
"id": {
"id": "0001"
},
"name": {
"last": {
"last": "bo"
},
"first": {
"first": "xue"
}
}
},
"name": {
"name": "st001"
}
}
]
}
?本文用最新的代码实现新的转换使结果更加理想。
代码如下:
package com.xue.tools;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.sf.json.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.QName;
import com.xue.tools.text.MyTextUtil;
public class Test2 {
public static void main(String[] args) throws UnsupportedEncodingException, DocumentException {
String textFromFile = MyTextUtil.getTextFromFile(new File("src/tt.xml"));
Document doc = DocumentHelper.parseText(textFromFile);
Map map = (Map) xml2map(doc.getRootElement());
System.out.println(JSONObject.fromObject(map));
}
private static Object xml2map(Element element) {
System.out.println(element);
Map map = new HashMap();
List elements = element.elements();
if (elements.size() == 0) {
map.put(element.getName(), element.getText());
if (!element.isRootElement()) {
return element.getText();
}
} else if (elements.size() == 1) {
map.put(elements.get(0).getName(), xml2map(elements.get(0)));
} else if (elements.size() > 1) {
// 多个子节点的话就得考虑list的情况了,比如多个子节点有节点名称相同的
// 构造一个map用来去重
Map tempMap = new HashMap();
for (Element ele : elements) {
tempMap.put(ele.getName(), ele);
}
Set keySet = tempMap.keySet();
for (String string : keySet) {
Namespace namespace = tempMap.get(string).getNamespace();
List elements2 = element.elements(new QName(string, namespace));
// 如果同名的数目大于1则表示要构建list
if (elements2.size() > 1) {
List list = new ArrayList();
for (Element ele : elements2) {
list.add(xml2map(ele));
}
map.put(string, list);
} else {
// 同名的数量不大于1则直接递归去
map.put(string, xml2map(elements2.get(0)));
}
}
}
return map;
}
}
?
结果如下:{
"classs": [
{
"id": "001",
"student": {
"id": "0001",
"name": {
"last": "bo",
"first": "xue"
}
},
"name": "st001"
},
{
"id": "001",
"student": {
"id": "0001",
"name": {
"last": "bo",
"first": "xue"
}
},
"name": "st001"
}
]
}
?
?