技术点: getResourceAsStream方法,dom4j的SaxReader解析xml
1.加载磁盘xml文件到内存中(InputStream)
package com.example.utils; import java.io.InputStream; public class Resource { public static InputStream load(String path) { return Resource.class.getClassLoader().getResourceAsStream(path); } }
2.引入dom4j的jar依赖包
<dependencies> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> </dependencies>
3.使用SaxReader类解析xml的内存输入流InputStream
public Properties parse(InputStream in) throws DocumentException { Properties prop = new Properties(); SAXReader saxReader = new SAXReader(); Document document = saxReader.read(in); Element rootElement = document.getRootElement(); List<Element> list = rootElement.selectNodes("//property"); for (Element element : list) { String name = element.attributeValue("name"); String value = element.attributeValue("value"); prop.setProperty(name, value); } return prop; }