Java使用dom4j查询xml元素
1.Java使用dom4j查询xml元素:
1.1book.xml文件如下:
<?xml version="1.0" encoding="UTF-8" ?>
<books>
<book>
<id>a1</id>
<name>疯狂Java讲义(附光盘)</name>
<author>李刚 编著</author>
<price>74.20</price>
<image>java.jpg</image>
<remark>
<![CDATA[疯狂源自梦想,技术成就辉煌 本书来自作者3年的Java培训经历,凝结了作者近3000个小时的授课经验,<br/>总结了几百个Java学员学习过程中的典型错误.]]></remark>
</book>
<book>
<id>a2</id>
<name>轻量级Java EE企业应用实战</name>
<author>李刚 编著</author>
<price>59.20</price>
<image>ee.jpg</image>
<remark>本书主要介绍以Spring+Hibernate为基础的Java EE应用.</remark>
</book>
<book>
</books>
2.使用dom4j查询xml元素:创建一个TestPath类:
2.1先要导入dom4j 的包++++++++++++++++++++++++++++++++++++++++++++++++++++
import java.util.LinkedList; import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class TestXPath {
public static void main(String[] args) throws DocumentException {
SAXReader reader = new SAXReader();
Document doc = reader.read(TestXPath.class.getResourceAsStream("/book.xml"));
// 后面再增加一个方法,根据id查询。
// 传入doc的目的,是为了多次使用同一个Document
List<Book> list = getBookList(doc);
list.forEach(e -> { System.out.println(e); });
System.out.println("========================================");
// 再次使用同一个Document进行查询
Book b = getBookById(doc, "3");
System.out.println(b); }
private static Book getBookById(Document doc, String id) {
Element e = (Element) doc.selectSingleNode("/books/book[id='" + id + "']");
Book b = toBook(e);
return b; }
private static Book toBook(Element e) {
Book b = new Book();
// 获取子元素中,名为author的元素的内容
String author = e.elementText("author");
String id = e.elementText("id");
String image = e.elementText("image");
String name = e.elementText("name");
String price = e.elementText("price");
String remark = e.elementText("remark");
b.setAuthor(author);
b.setId(id);
b.setImage(image);
b.setName(name);
b.setPrice(price);
b.setRemark(remark);
return b; }
private static List<Book> getBookList(Document doc) {
@SuppressWarnings("unchecked")
List<Element> nodeList = doc.selectNodes("/books/book");
// System.out.println(nodeList);
List<Book> result = new LinkedList<>();
nodeList.forEach(e -> { Book b = toBook(e); result.add(b); });
return result; } }