import java.io.InputStream; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class Dom4JXmlConvert { /** * dom4j解析xml * * @param in * @return */ @SuppressWarnings("unchecked") public static List<Map<String, Object>> convert(InputStream in) { long start = System.currentTimeMillis(); List<Map<String, Object>> lst = new LinkedList<>(); SAXReader saxReader = new SAXReader(); try { Document document = saxReader.read(in); // 获取根节点 Element root = document.getRootElement(); // 迭代根节点下的所有子节点 Iterator<Element> itertor = root.elementIterator(); Element eleNext = null; // 遍历子节点 while (itertor.hasNext()) { eleNext = itertor.next(); Map<String, Object> tmp = parseElement(eleNext); lst.add(tmp); } System.out.println("本次解析XML耗时:" + (System.currentTimeMillis() - start)); } catch (DocumentException e) { e.printStackTrace(); } return lst; } @SuppressWarnings({ "unchecked" }) private static Map<String, Object> parseElement(Element ele) { Map<String, Object> map = new LinkedHashMap<String, Object>(); // 遍历节点属性 Iterator<Attribute> iterAttr = ele.attributeIterator(); // 遍历时的中间遍量 Attribute attr = null; // 遍历 while (iterAttr.hasNext()) { attr = iterAttr.next(); map.put(attr.getQName().getName(), attr.getValue()); } // 如果该节点没有子节点,则添加标签名和标签中间的字符到map,如果还有子节点,递归遍历 Iterator<Element> itertor = ele.elementIterator(); if (!itertor.hasNext()) { map.put(ele.getName(), ele.getStringValue()); } else { List<Map<String, Object>> lst = new LinkedList<>(); while (itertor.hasNext()) { lst.add(parseElement(itertor.next())); } map.put(ele.getName(), lst); } return map; } }
测试解析spring的配置文件,自定义文件,均可正常解析