xml解析技术介绍
dom4j
-
导入相关依赖 -
将要读取的xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<books>
<book sn="SN123123123">
<name>辟邪剑谱</name>
<price>99</price>
<author>班主任</author>
</book>
<book sn="SN123123123">
<name>葵花宝典</name>
<price>99.9</price>
<author>班长</author>
</book>
</books>
- 生成对应对象的set,get,以及toString方法
package com.atguigu.pojo;
import java.math.BigDecimal;
public class Book {
private String sn;
private String name;
public Book(String sn, String name, BigDecimal price, String author) {
this.sn = sn;
this.name = name;
this.price = price;
this.author = author;
}
private BigDecimal price;
public Book() {
}
private String author;
public void setSn(String sn) {
this.sn = sn;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public void setAuthor(String author) {
this.author = author;
}
public String getSn() {
return sn;
}
public String getName() {
return name;
}
public BigDecimal getPrice() {
return price;
}
public String getAuthor() {
return author;
}
@Override
public String toString() {
return "Book{" +
"sn='" + sn + '\'' +
", name='" + name + '\'' +
", price=" + price +
", author='" + author + '\'' +
'}';
}
}
- 读取
package com.atguigu.pojo;
import org.dom4j.Document;
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(){
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read("src/books.xml");
System.out.println(document);
}catch (Exception e){
e.printStackTrace();
}
}
@Test
public void test2() throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read("src/books.xml");
Element rootElement = document.getRootElement();
List<Element> books = rootElement.elements("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));
}
}
}
|