文章目录
- 1. properties
- 2. XML
- (1) dom4j
- (2) XPath
1. properties
// 创建properties对象用于读取properties文件Properties properties = new Properties();properties.load(new FileReader("src/main/resources/test.properties"));String name = properties.getProperty("name");String age = properties.getProperty("age");System.out.println(name);System.out.println(age);
2. XML
(1) dom4j
maven坐标
<dependency><groupId>dom4j</groupId><artifactId>dom4j</artifactId><version>1.1</version></dependency>
// 获取解析器对象SAXReader xmlReader = new SAXReader();// 获取xml文件Document student = xmlReader.read(new File("student.xml"));Element root = student.getRootElement();// 获取根标签List<Element> elements = root.elements();// 获取根标签中的所有标签// 获取第一个元素的name标签的值String name = elements.get(0).element("name").getText();// 获取第一个元素的age标签的值String age = elements.get(0).element("age").getText();System.out.println(name);System.out.println(age);
(2) XPath
使用路径表达式进行解析
// 获取解析器对象SAXReader xmlReader = new SAXReader();Document student = xmlReader.read(new File("src\\main\\resources\\student.xml"));// 获取一个Node node = student.selectSingleNode("/students/student/name");System.out.println(node.getText());//获取多个List<Element> list = student.selectNodes("/students/student/*");for (Element element : list) {System.out.println(element.getText());}