文章目录
- [1. properties](#1. properties)
- [2. XML](#2. XML)
-
- [(1) dom4j](#(1) dom4j)
- [(2) XPath](#(2) XPath)
1. properties
java
// 创建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坐标
xml
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.1</version>
</dependency>
java
// 获取解析器对象
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
使用路径表达式进行解析
xml
// 获取解析器对象
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());
}