简单使⽤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>
我把l放在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:/l");
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 = ad(xmlfile);//从xml⽂件获取数据
Document document = ad(new Bytes("utf-8")));//读取xml字符串,注意这⾥要转成输⼊流        Element root = RootElement();//获取根元素使用dom4j解析xml文件
List<Element> childElements = root.elements();//获取当前元素下的全部⼦元素
for (Element child : childElements) {//循环输出全部book的相关信息
List<Element> books = child.elements();
for (Element book : books) {
String name = Name();//获取当前元素名
String text = Text();//获取当前元素值
System.out.println(name + ":" + text);
}
}
//获取第⼆条书籍的信息
Element book2 = (1);
Element author = book2.element("author");//根据元素名获取⼦元素
Element title = book2.element("title");
Element publisher = book2.element("publisher");
System.out.println("作者:" + Text());//获取元素值
System.out.println("书名:" + Text());
System.out.println("出版社:"+Text());
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。