总的文件目录为
第一步首先要dom4j的jar包等
第二步要有相对应的XML文件
XML文件内容为
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book sn="SN12341232">
<name>辟邪剑谱</name>
<price>9</price>
<author>班主任</author>
</book>
<book sn="SN12341231">
<name>葵花宝典</name>
<price>99</price>
<author>班长</author>
</book>
</books>
第三步创造JAVA类
import java.math.BigDecimal;
public class book {
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;
}
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 book(String value, String snValue, String nameText, String priceText) {
}
private String sn;
private String name;
private Double price;
private String author;
}
第四步进行解析XML文件,形成JAVA类
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import java.util.List;
public class Bookstext {
@Test
public void text2() throws DocumentException {
//1.创建SAXReader对象
SAXReader saxReader = new SAXReader();
//2.读取xml文件
Document read = saxReader.read("src/books.xml");
//3.通过Document对象获取根元素
Element rootElement = read.getRootElement();
//4.通过根元素获取book
//element()和elements()都可以获取标签名查找子元素
List<Element> book = rootElement.elements("book");
//5.遍历,每一个book标签转换为Book类
for (Element books:book){
//asXML()把标签对象转化为标签字符串
// Element name = books.element("name");
//getText()可以获取标签中的文本内容
// String nameText = name.getText();
//elementText()可以获取标签名里面的内容,就不需要像上面那样去处理了
String nameText = books.elementText("name");
String priceText = books.elementText("price");
String authorText = books.elementText("author");
//attributeValue()可以获取标签属性的值
String snValue = books.attributeValue("sn");
//这里要和声明时的顺序一致
System.out.println(new book(snValue,nameText,priceText,authorText));
}
}
}