创建一个图书的book.xml
文件
<?xml version="1.0" encoding="utf-8" ?>
<books>
<book sn="SN1232131511535">
<name>时间简史</name>
<author>霍金</author>
<price>75</price>
</book>
<book sn="SN1232131511323">
<name>java</name>
<author>张三</author>
<price>6.6</price>
</book>
</books>
根据XML文件创建对应的Book
类
public class Book {
private String sn;
private String name;
private float price;
private String author;
public Book() {
}
public Book(String sn, String name, float 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 float getPrice() {
return price;
}
public void setPrice(float 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 + '\'' +
'}';
}
}
使用dom4j
读取xml
文件。
@Test
public void test1() throws Exception {
//创建一个saxReader输入流,去读取xml配置文件,生成Document对象
SAXReader saxReader = new SAXReader();
Document document = saxReader.read("src/book.xml");
System.out.println(document);
}
把XML文件中的<book></book>
都解析成对应的Book
类的对象实例
@Test
public void test2() throws DocumentException {
//1.读取book.xml文件
SAXReader saxReader = new SAXReader();
Document document = saxReader.read("src/book.xml");
//2.通过Document对象获取根元素
Element rootElement = document.getRootElement();
//3.通过根元素获取book标签对象
List<Element> books = rootElement.elements("book");
//4.遍历,处理每个book标签转换成Book类
for (Element book : books){
//asXML()把标签对象,转换为标签字符串
Element nameElement = book.element("name");
//getText()可以获取标签中的文本内容
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, Float.parseFloat(priceText), authorText));
}
}
输出结果: