dom4j是第三方的解析技术。需要使用第三方提供的类库才可以解析XML文件。
使用 dom4j 就需要到 dom4j 官网下载dom4j的jar包或使用Maven坐标。
解析如下xml
<?xml version="1.0" encoding="utf-8"?>
<books>
<!-- sn 序列号-->
<book sn="SN123456">
<name>时间简史</name>
<author>霍金</author>
<price>100</price>
</book>
<book sn="SN123457">
<name>java从入门到精通</name>
<author>James Gosling</author>
<price>120</price>
</book>
</books>
- 导入dom4j jar 包
- 创建对应的Book类
package com.zx.pojo;
import java.math.BigDecimal;
/**
* @author 挚爱之夕
* @version 1.0
* @implSpec 书
* @since 2022 - 07 - 06 - 11:08
*/
public class Book {
private Integer id;
private String name;
private String author;
private BigDecimal price;
private Integer sales;
private Integer stock;
private String imgPath = "static/img/default.jpg";
public Book(Integer id, String name, String author, BigDecimal price, Integer sales, Integer stock, String imgPath) {
this.id = id;
this.name = name;
this.author = author;
this.price = price;
this.sales = sales;
this.stock = stock;
//要求给定的图书封面图片不为空
if(imgPath != null && !"".equals(imgPath))
this.imgPath = imgPath;
}
public Book() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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 BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Integer getSales() {
return sales;
}
public void setSales(Integer sales) {
this.sales = sales;
}
public Integer getStock() {
return stock;
}
public void setStock(Integer stock) {
this.stock = stock;
}
public String getImgPath() {
return imgPath;
}
public void setImgPath(String imgPath) {
this.imgPath = imgPath;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", author='" + author + '\'' +
", price=" + price +
", sales=" + sales +
", stock=" + stock +
", imgPath='" + imgPath + '\'' +
'}';
}
}
- 解析
public void test2() throws DocumentException {
//创建输入流
SAXReader saxReader = new SAXReader();
//读取 获取Document对象
Document document = saxReader.read("src/books.xml");
//获取 元素根节点
Element rootElement = document.getRootElement();
//获取根标签 下的所有 book 标签
List<Element> books = rootElement.elements("book");
for (Element book:books
) {
//asXML() 将标签对象 转为 xml文本
// System.out.println(book.asXML());
//element() 获取指定名称标签元素
Element nameElement = book.element("name");
//elementText() 直接获取标签文本
String authorText = book.elementText("author");
String priceText = book.elementText("price");
//创建Book对象 attributeValue()获取标签指定属性的值
Book book1 = new Book(book.attributeValue("sn") ,nameElement.getText(), authorText, Double.parseDouble(priceText));
System.out.println(book1);
}
}