public class XmlToMapDemp {
/*
xml内容示例
<?xml version="1.0" encoding="UTF-8"?>
<ROOT>
<ONE>
<TWO>value-two</TWO>
</ONE>
</ROOT>
*/
public static void main(String[] args) {
Map<String, Object> map = XmlUtils.xmlToMap("src/main/java/demo.xml");// 目标xml地址
System.out.println(map); //{ROOT={ONE={TWO=value-two}}}
/*
* map中的key是和对应的xml文件中的标签相对应
* 注意:不能转换成 Map<String, String> 类型
*/
Map<String, Object> root = (Map<String, Object>) map.get("ROOT");
System.out.println(root); //{ONE={TWO=value-two}}
Map<String, Object> one = (Map<String, Object>) root.get("ONE");
System.out.println(one); //{TWO=value-two}
Object two = one.get("TWO");
System.out.println(two.toString()); //value-two
}
}
自定义工具类
package com.springboot.util;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class XmlUtils {
public static Map<String, Object> xmlToMap(String xmlFilePath) {
try {
SAXReader reader = new SAXReader();
Document document = reader.read(xmlFilePath);
Element root = document.getRootElement();
Iterator it = root.elementIterator();
// 递归 xml 转 map
Map<String, Object> rootMap = getContentMap(root, it);
return rootMap;
} catch (DocumentException e) {
e.printStackTrace();
}
return null;
}
private static Map<String, Object> getContentMap(Element root, Iterator it){
Map<String, Object> rootMap = new HashMap<>();
Map<String, Object> nextRootMap = new HashMap<>();
while(it.hasNext()){
Element nextRoot = (Element)it.next();
Iterator nextIt = nextRoot.elementIterator();
if(nextIt.hasNext()){ //当前xml标签下,存嵌套了其他标签
Map<String, Object> nextContentMap = getContentMap(nextRoot, nextIt);
nextRootMap.putAll(nextContentMap);
}else{ //当前xml标签下,只有值,未嵌套其他标签
nextRootMap.put(nextRoot.getName(), nextRoot.getTextTrim());
}
}
rootMap.put(root.getName(), nextRootMap);
return rootMap;
}
}