|
@ -13,6 +13,7 @@ import org.dom4j.*;
|
|
|
import org.dom4j.io.OutputFormat;
|
|
|
import org.dom4j.io.SAXReader;
|
|
|
import org.dom4j.io.XMLWriter;
|
|
|
import org.dom4j.tree.DefaultAttribute;
|
|
|
import org.slf4j.Logger;
|
|
|
import org.slf4j.LoggerFactory;
|
|
|
import org.springframework.util.StringUtils;
|
|
@ -544,13 +545,13 @@ public class XMLUtil {
|
|
|
ele2map(map, rootElement);
|
|
|
System.out.println(map);
|
|
|
// 到此xml2map完成,下面的代码是将map转成了json用来观察我们的xml2map转换的是否ok
|
|
|
String string = JSONObject.fromObject(map).toString();
|
|
|
String string = net.sf.json.JSONObject.fromObject(map).toString();
|
|
|
System.out.println(string);
|
|
|
return map;
|
|
|
}
|
|
|
|
|
|
private static void ele2map(Map map, Element ele) {
|
|
|
System.out.println(ele);
|
|
|
|
|
|
private static void ele2map(Map map, Element ele) {
|
|
|
// 获得当前节点的子节点
|
|
|
List<Element> elements = ele.elements();
|
|
|
if (elements.size() == 0) {
|
|
@ -560,7 +561,13 @@ public class XMLUtil {
|
|
|
// 只有一个子节点说明不用考虑list的情况,直接继续递归即可
|
|
|
Map<String, Object> tempMap = new HashMap<String, Object>();
|
|
|
ele2map(tempMap, elements.get(0));
|
|
|
map.put(ele.getName(), tempMap);
|
|
|
//设置标签属性
|
|
|
setAttributes(tempMap,elements.get(0));
|
|
|
if (tempMap.size()==1){
|
|
|
map.put(ele.getName(), ele.getText());
|
|
|
}else {
|
|
|
map.put(ele.getName(), tempMap);
|
|
|
}
|
|
|
} else {
|
|
|
// 多个子节点的话就得考虑list的情况了,比如多个子节点有节点名称相同的
|
|
|
// 构造一个map用来去重
|
|
@ -578,19 +585,52 @@ public class XMLUtil {
|
|
|
for (Element element : elements2) {
|
|
|
Map<String, Object> tempMap1 = new HashMap<String, Object>();
|
|
|
ele2map(tempMap1, element);
|
|
|
setAttributes(tempMap1,element);
|
|
|
list.add(tempMap1);
|
|
|
|
|
|
}
|
|
|
map.put(string, list);
|
|
|
} else {
|
|
|
// 同名的数量不大于1则直接递归去
|
|
|
Map<String, Object> tempMap1 = new HashMap<String, Object>();
|
|
|
ele2map(tempMap1, elements2.get(0));
|
|
|
map.put(string, tempMap1);
|
|
|
setAttributes(tempMap1,elements2.get(0));
|
|
|
if (tempMap1.containsKey(string)) {
|
|
|
map.put(string, tempMap1.get(string));
|
|
|
}else {
|
|
|
map.put(string, tempMap1);
|
|
|
}
|
|
|
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
*
|
|
|
* 设置属性值(xml转map)
|
|
|
* @param map
|
|
|
* @param element
|
|
|
*/
|
|
|
public static void setAttributes(Map map,Element element){
|
|
|
List list = element.attributes();
|
|
|
Map<String,Object> attrMap = null;
|
|
|
DefaultAttribute e = null;
|
|
|
if (!list.isEmpty()) {
|
|
|
attrMap = new HashMap<>();
|
|
|
for (int i = 0; i < list.size(); i++) {
|
|
|
e = (DefaultAttribute) list.get(i);
|
|
|
attrMap.put(e.getName(),e.getText());
|
|
|
}
|
|
|
attrMap.put("text",element.getText());
|
|
|
}
|
|
|
|
|
|
if (attrMap!=null && !attrMap.isEmpty()){
|
|
|
map.put(element.getName(),attrMap);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static Map xmltoMap(String xml) {
|