引入的 jar 包
xml 文件
<?xml version="1.0" encoding="UTF-8" ?>
<books>
<book sn = "book1001">
<name>
陆炳生漂流记
</name>
<author>
x先生
</author>
<price>
23
</price>
</book>
<book sn = "book1002">
<name>
从吃泡面的日子到入土
</name>
<author>
w先生
</author>
<price>
99
</price>
</book>
</books>
Java 类
package com.huke;
/**
* xml 文件对应的类,理解为 books.xml 的映射类
*/
public class Book {
private String sn;
private String name;
private String author;
private Double price;
public Book() {
}
public Book(String sn, String name, String author, Double price) {
this.sn = sn;
this.name = name;
this.author = author;
this.price = price;
}
public String getSn() {
return sn;
}
public void setSn(String sn) {
this.sn = sn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"sn='" + sn + '\'' +
", name='" + name + '\'' +
", author='" + author + '\'' +
", price=" + price +
'}';
}
}
将 xml 文件解析为 java 对象
package com.huke;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import java.util.List;
public class dom4jTest {
@Test
public void test1() throws Exception {
// 创建一个 SaxReader 输入流,去读取 xml 配置文件,生成 Document 对象
SAXReader saxReader = new SAXReader();
Document document = saxReader.read("src/books.xml");
System.out.println(document);
}
/**
* 将 xml 文件解析为 Java 对象
*/
@Test
public void test02() throws Exception {
// 1 读取 xml 文件
SAXReader saxReader = new SAXReader();
// 在 Junit 测试中,相对路径是从模块名开始算
Document document = saxReader.read("src/books.xml");
// 2 通过 Document 对象获取根元素
Element rootElement = document.getRootElement();
// 3 通过根元素获取 book 标签对象
// element() 和 elements() 都是通过标签名查找子元素
List<Element> books = rootElement.elements("book");
// 4 遍历,处理每个 book 标签转换为 Book 类
for(Element ele : books){
// asXML() 把标签名对象,转换为标签字符串
Element nameElement = ele.element("name");
// System.out.println(nameElement.asXML());
Element author = ele.element("author");
Element price = ele.element("price");
// getText() 可以获取标签中的文本内容
String nameText = nameElement.getText().trim();
String authorText = author.getText().trim();
String priceText = price.getText();
// attributeValue() 根据标签的属性名获取属性的文本内容
String sn = ele.attributeValue("sn");
System.out.println(new Book(sn,nameText,authorText,Double.parseDouble(priceText)));
}
}
}
运行 test2() 方法结果
Book{sn='book1001', name='陆炳生漂流记', author='x先生', price=23.0}
Book{sn='book1002', name='从吃泡面的日子到入土', author='w先生', price=99.0}