import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class XmlUtil {
//XML转为MAP
public static Map<String, Object> xmlToMap(String str) throws Exception {
Map<String, Object> resultMap = new LinkedHashMap<>();
String st ="";
int length = str.length();
for (int i = 0; i < length;i++) {
char c = str.charAt(i);
if (c!=10){
st = st+String.valueOf(c);
}
}
Document doc = DocumentHelper.parseText(st);
Element rootElement = doc.getRootElement();//根目录 个数肯定为1
List<Element> childrenElementList = rootElement.elements();//二级目录 个数大于等于1
for (Element e : childrenElementList) {
List<Element> thirdElementList = e.elements();//三级目录
if (thirdElementList.size() > 0) {//三级目录大于0
element2Map(resultMap, e);
} else {//三级目录等于0 直接将二级的元素存到map
resultMap.put(e.getName(), e.getText());
}
}
return resultMap;
}
/**
* XML解析为Map
*/
public static Map<String, Object> element2Map(Map<String, Object> map, Element rootElement) throws Exception {
Map<String, Object> tempMap = new LinkedHashMap<>();
List<Element> childrenElementList = rootElement.elements();//三级目录(肯定大于0因为外层已经判断了)
//遍历所有子节点
for (Element e : childrenElementList) {
List<Element> nextElementList = e.elements();//四级目录
if (nextElementList.size() > 0) {//四级目录大于0则继续循环
element2Map(tempMap, e);
} else {//四级目录等于0则将三级目录存进去
tempMap.put(e.getName(), e.getText());
}
}
map.put(rootElement.getName(), tempMap);
return map;
}
//MAP转为XML
public static String mapToXml(LinkedHashMap map){
StringBuffer sb = new StringBuffer();
map.forEach((key,value)->{
sb.append("<"+key+">"+value+"</"+key+">"+"\n");
});
return sb.toString();
}
public static void main(String[] args) {
LinkedHashMap<Object, Object> map = new LinkedHashMap<>();
map.put("abc","测试1");
map.put("fsds","测试2");
map.put("wes","测试3");
map.put("hgjh","测试4");
map.put("nbnb","测试5");
String s = mapToXml(map);
System.out.println(s);
}
}
08-09
607
04-01
513
09-21
863