使用Dom4j解析xml文件一般操作

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='周杰伦'}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值