| 实现效果使用dom4j,实现将一个books.xml,解析为book类的对象:1、xml文档
 
  2、book类的信息
 
  3、转化后的情况
 
  实现1、导入dom4j的相关jar包,以及用于单元测试的相关jar包
  2、xml文档的内容:
 <?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>
 3、book类的情况: package com.athanchang.pojo;
import java.math.BigDecimal;
public class book {
    private String sn;
    private String name;
    private BigDecimal price;
    private String author;
    
    
    
    public book(String sn, String name, BigDecimal price, String author) {
        this.sn = sn;
        this.name = name;
        this.price = price;
        this.author = author;
    }
    public 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 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 + '\'' +
                '}';
    }
}
 4、实现转换功能的代码 package com.athanchang.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  test2() throws Exception {
        
        SAXReader saxReader = new SAXReader();
        
        Document document = saxReader.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));
        }
    }
}
 
 行百里者,半九十! |