1.加载dom4j
依赖:
<!-- https://mvnrepository.com/artifact/org.dom4j/dom4j -->
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.3</version>
</dependency>
2.解析xml文件:
package com.example.demo;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class Dom4jTest {
public static void main(String[] args) throws DocumentException {
SAXReader saxReader = new SAXReader();
// Document document = saxReader.read("src/main/resources/log.xml");
Document document = saxReader.read(Dom4jTest.class.getClassLoader().getResourceAsStream("log.xml"));
System.out.println(document);
// 获取根元素
Element rootElement = document.getRootElement();
System.out.println(rootElement.getName());
// element(String name) elements() elements(String name)
List<Element> books = rootElement.elements("book");
List<Book> bookList = new ArrayList<>();
for (Element book : books) {
// asXml()将标签对象转换为标签字符串
Element nameElement = book.element("name");
String name = nameElement.getText();
// elementText(String tagName)直接获取指定标签名的文本内容
String price = book.elementText("price");
String author = book.elementText("author");
String sn = book.attributeValue("sn");
bookList.add(new Book(name, BigDecimal.valueOf(Double.parseDouble(price)),author,sn));
}
System.out.println(bookList);
}
}