springboot使用dom4j、Xpath解析复杂xml,请给出maven依赖已经详细的代码示例
时间: 2024-05-06 13:20:49 浏览: 174
dom4j 解析xml实例
Maven依赖:
```xml
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.3</version>
</dependency>
```
代码示例:
```java
import java.io.File;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
public class XmlParser {
public static void main(String[] args) throws Exception {
SAXReader reader = new SAXReader();
Document doc = reader.read(new File("example.xml"));
// 使用xpath获取节点
Element root = doc.getRootElement();
List<Node> nodes = root.selectNodes("//person[@age>20]");
for (Node node : nodes) {
Element element = (Element) node;
System.out.println("name: " + element.attributeValue("name"));
System.out.println("age: " + element.attributeValue("age"));
System.out.println("address: " + element.selectSingleNode("address").getText());
System.out.println("phone: " + element.selectSingleNode("phone").getText());
System.out.println("===========================");
}
}
}
```
阅读全文