dom4j解析xml文件
一、导包,编写bean类和测试类
二、编码测试,通过dom4j生成bean对象
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book sn="SN12341232">
<name>辟邪剑谱</name>
<price>9.9</price>
<author>班主任</author>
</book>
<book sn="SN12341231">
<name>葵花宝典</name>
<price>99.99</price>
<author>班长</author>
</book>
</books>
Book.java
package com.shungen.pojo;
/**
* @author wangshungen
* @version 1.0
* @description: TODO
* @date 2021/12/20 17:40
*/
public class Book {
private String sn;
private String name;
private Double price;
private String author;
public Book() {
}
public Book(String sn, String name, Double price, String author) {
this.sn = sn;
this.name = name;
this.price = price;
this.author = author;
}
@Override
public String toString() {
return "Book{" +
"sn='" + sn + '\'' +
", name='" + name + '\'' +
", price=" + price +
", author='" + author + '\'' +
'}';
}
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 Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
测试类
package com.shungen.pojo;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import org.xml.sax.SAXException;
import java.util.List;
/**
* @author wangshungen
* @version 1.0
* @description: TODO
* @date 2021/12/20 17:44
*/
public class Dom4jTest {
public static void main(String[] args) {
}
@Test
public void test01() throws SAXException, DocumentException {
//
SAXReader saxReader = new SAXReader();
Document document = saxReader.read("src/books.xml");
System.out.println(document);
}
/**
* 读取books.xml文件,生成Book类
*/
@Test
public void test02() throws DocumentException {
//1、通过SAXReader解析器(SAXReader流对象---<这个说法我不知道是不是正确的,但其中肯定涉及到流对象>)读取book.xml文件,并通过read方法获取Document对象
SAXReader saxReader = new SAXReader();
Document document = saxReader.read("src/books.xml");
//2、通过Document对象获取根元素(Element对象)
Element rootElement = document.getRootElement();
// System.out.println(rootElement);
//3、通过根元素获取book标签对象
List<Element> books = rootElement.elements("book");
//4、遍历,处理每个Book标签转换为Book对象
for(Element book:books){
/* //(1)asXML()把标签对象(Element对象)转换为标签字符串
// System.out.println(book.asXML());
Element nameElement = book.element("name");
// System.out.println(nameElement.asXML());
//(2)getText() 可以获取标签里面的内容
String nameText = nameElement.getText();
System.out.println(nameText);//获取book下name标签里面的内容*/
//所以,综上,先获取所有的子标签和属性
String nameText = book.elementText("name");
String priceText = book.elementText("price");
String authorText = book.elementText("author");//elementText()直接获取调用者的标签值
String snText = book.attributeValue("sn");
System.out.println(new Book(snText,nameText,Double.parseDouble(priceText),authorText));
}
}
}