xml文件:
<?xml version="1.0" encoding="UTF-8" ?>
<books>
<book sn="SN001">
<name>java</name>
<price>33</price>
<author>刘德华</author>
</book>
<book sn="SN002">
<name>C++</name>
<price>44</price>
<author>周杰伦</author>
</book>
</books>
Book实体类:
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;
}
/**
*set get方法省略
*/
@Override
public String toString() {
return "Book{" +
"sn='" + sn + '\'' +
", name='" + name + '\'' +
", price=" + price +
", author='" + author + '\'' +
'}';
}
}
测试类:
public class Dom4jTest {
@Test
public void test1() throws DocumentException {
//创建一个SaxReader输入流,读取xml文件,生成Document对象
SAXReader saxReader=new SAXReader();
Document document = saxReader.read("books.xml");
//获取根元素
Element root = document.getRootElement();
//System.out.println(root);
//获得所有book子元素
List<Element> books = root.elements("book");
//遍历封装
for(Element book:books){
//取属性 sn 的值
String sn=book.attributeValue("sn");
//取子元素 name 的数据
String name=book.elementText("name");
Double price=Double.parseDouble(book.elementText("price"));
String author=book.elementText("author");
Book b=new Book(sn,name,price,author);
System.out.println(b);
}
}
}
输出结果:
Book{sn='SN001', name='java', price=33.0, author='刘德华'}
Book{sn='SN002', name='C++', price=44.0, author='周杰伦'}