使用dom4j实现java解析XML实例

由于要给一个做毕设的学妹讲java解析XML,所以我把网上的一些资料整合了一下,写了一个实例,在此跟大家分享。

【此文的目的不是大而全地讲解dom4j,而是给大家一个比较快上手的途径】

dom4j应该说是java解析XML的首选工具了,具体的优势可以参考IBM developer社区的一篇文章。

第一步:导入dom4j的jar包。下载地址:http://sourceforge.net/projects/dom4j

 

第二步:确定需要解析的XML,解析的目标是获取不同作者的书籍价格,文件books.xml放在工程目录下。

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <books>
 3     <book id="1">
 4         <author>Zhou</author>
 5         <price>50</price>
 6     </book>
 7     <book id="2">
 8         <author>Chen</author>
 9         <price>70</price>
10     </book>
11     <book id="3">
12         <author>Hou</author>
13         <price>60</price>
14     </book>
15 </books>

 

第三步:确定解析时需要调用的成员函数

1.确定读取XML文档时使用的read函数

1 public Document read(String fileName) throws MalformedURLException, DocumentException {
2            SAXReader reader = new SAXReader();
3            Document document = reader.read(fileName);//Reads a Document from the given URL or filename using SAX.
4            return document;
5         }

2.确定获得作者的函数

String author = element.elementText("author");//get the text of author node

3.确定获得书价的函数

String price = element.elementText("price");//get the text of price node

 

第四步,确定main函数

1.new一个对象

TestDom4j testDom4j = new TestDom4j();

2.读取books.xml,因为文档就放在工程目录下,所以此处就写文件名就可以了

Document doc4j = testDom4j.read("books.xml");

3.获得XML的根节点

Element root = doc4j.getRootElement();

4.获得所有名称为"book"的节点(元素)

List nodes = root.elements("book");    

5.遍历这些book节点元素,并对每一个book节点元素获取其作者和书价

for (Iterator it = nodes.iterator(); it.hasNext();) {      
                Element nextElement = (Element) it.next();//do something to every node:
                testDom4j.getAuthor(nextElement);
                testDom4j.getPrice(nextElement);     
            }

6.由于在读取XML的过程中会抛出异常,所以我们需要在main函数中加入“try...catch...”机制

1 try{
2             //do something
3             //...
4 
5         }catch(Exception e){
6             e.getStackTrace();
7         }

 

完整代码如下:

 1 import java.net.MalformedURLException;
 2 import java.util.Iterator;
 3 import java.util.List;
 4 
 5 import org.dom4j.Document;
 6 import org.dom4j.DocumentException;
 7 import org.dom4j.Element;
 8 import org.dom4j.io.SAXReader;
 9 
10 public class TestDom4j {
11     
12     public Document read(String fileName) throws MalformedURLException, DocumentException {
13            SAXReader reader = new SAXReader();
14            Document document = reader.read(fileName);//Reads a Document from the given URL or filename using SAX.
15            return document;
16         }
17     
18     public void getAuthor(Element element) {
19         String author = element.elementText("author");//get the text of author node
20         System.out.println(author);
21      }
22     
23     public void getPrice(Element element) {
24         String price = element.elementText("price");//get the text of price node
25         System.out.println(price);
26      }
27 
28     public static void main(String[] args) {
29         TestDom4j testDom4j = new TestDom4j();
30         try{
31             Document doc4j = testDom4j.read("books.xml");//read book.xml
32             Element root = doc4j.getRootElement();    //get root of book.xml
33             
34             List nodes = root.elements("book");    //get all book nodes
35             for (Iterator it = nodes.iterator(); it.hasNext();) {      
36                 Element nextElement = (Element) it.next();//get author or price node      
37                 //do something to every node:
38                 testDom4j.getAuthor(nextElement);
39                 testDom4j.getPrice(nextElement);     
40             }
41         }catch(Exception e){
42             e.getStackTrace();
43         }
44     }
45 }

 

运行结果如下:

Zhou
50
Chen
70
Hou
60

 

【注】

1.dom4j对XPath有良好的支持,如访问一个节点,可直接用Xpath选择。

1 //按前文获取doc4j后:
2 String xpath ="//book[author=Chen]/price";
3 String result = doc4j.selectSingleNode(xpath).getText();//获取作者为"Chen"的那本书的书价

 具体语法可参考:http://www.w3school.com.cn/xpath/

2.在dom4j中使用Xpath需要导入jaxen.jar

下载地址:http://ishare.iask.sina.com.cn/f/21967874.html

posted @ 2014-03-31 09:35  Lettifay  阅读(904)  评论(1编辑  收藏  举报