简单使用SAXReader解析xml数据

​
<books>
    <book>
        <author>Thomas</author>
        <title>Java从入门到放弃</title>
        <publisher>UCCU</publisher>
    </book>
    <book>
        <author>小白</author>
        <title>MySQL从删库到跑路</title>
        <publisher>Go Die</publisher>
    </book>
    <book>
        <author>PHPer</author>
        <title>Best PHP</title>
        <publisher>PHPchurch</publisher>
    </book>
</books>

​

我把book.xml放在D盘的根目录下,这样读取时能比较方便些……

下面是代码:

package com;
 
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
 
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.List;
 
public class SAXReaderXML {
    public static void main(String[] args) throws Exception {
        SAXReader reader = new SAXReader();
        File xmlfile = new File("D:/books.xml");
        String xml = "<books><book><author>Thomas</author><title>Java从入门到放弃</title><publisher>UCCU</publisher>" +
                "</book><book><author>小白</author><title>MySQL从删库到跑路</title><publisher>GoDie</publisher></book>" +
                "<book><author>PHPer</author><title>BestPHP</title><publisher>PHPchurch</publisher></book></books>";
        Document fileDocument = reader.read(xmlfile);//从xml文件获取数据
        Document document = reader.read(new ByteArrayInputStream(xml.getBytes("utf-8")));//读取xml字符串,注意这里要转成输入流
        Element root = document.getRootElement();//获取根元素
        List<Element> childElements = root.elements();//获取当前元素下的全部子元素
 
        for (Element child : childElements) {//循环输出全部book的相关信息
            List<Element> books = child.elements();
            for (Element book : books) {
                String name = book.getName();//获取当前元素名
                String text = book.getText();//获取当前元素值
                System.out.println(name + ":" + text);
            }
        }
        //获取第二条书籍的信息
        Element book2 = childElements.get(1);
        Element author = book2.element("author");//根据元素名获取子元素
        Element title = book2.element("title");
        Element publisher = book2.element("publisher");
        System.out.println("作者:" + author.getText());//获取元素值
        System.out.println("书名:" + title.getText());
        System.out.println("出版社:"+publisher.getText());
    }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值