<?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>
上面是一个books.xml文件
要把它通过dom4j映射,需要先在同模块下新建lib目录导入dom4j的jar包
然后建一个Book类:
import java.math.BigDecimal;
public class Book {
private String sn;
private String name;
private BigDecimal price;
private String author;
public Book() {
}
public Book(String sn, String name, BigDecimal price, String author) {
this.sn = sn;
this.name = name;
this.price = price;
this.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 BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "Book{" +
"sn='" + sn + '\'' +
", name='" + name + '\'' +
", price=" + price +
", author='" + author + '\'' +
'}';
}
}
最后是在另一个新建的java类中完成映射。
//在IDEA中可以通过@Test注解进行测试(需要下载相关junit的jar包)
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.List;
public class Dom4jTest {
@Test
public void test1() throws DocumentException {
SAXReader saxReader=new SAXReader();
Document document=saxReader.read("src/books.xml"); //这里采用了相对路径的写法
System.out.println(document);
}
@Test
public void test2() throws DocumentException {
//1.读取XML文件
SAXReader reader=new SAXReader();
Document document=reader.read("src/books.xml");
//2.读取根元素
Element rootElement= document.getRootElement();
//3.通过根元素获取book标签对象
List<Element> books= rootElement.elements("book");
//4.遍历,处理每个book标签对象转为Book类对象
for(Element book:books){
Element nameElement= book.element("name");
String nameText=nameElement.getText();
String priceText= book.elementText("price");
String authorText= book.elementText("author");
String snValue=book.attributeValue("sn");
System.out.println(new Book(snValue,nameText,new BigDecimal(priceText),authorText));
}
}
}