天天看點

dom4j的解析執行個體

book.xml資料如下:

<books>  

    <book>  

        <author>Thomas</author>  

        <title>Java從入門到放棄</title>  

        <publisher>UCCU</publisher>  

    </book>  

        <author>小白</author>  

        <title>MySQL從删庫到跑路</title>  

        <publisher>Go Die</publisher>  

        <author>PHPer</author>  

        <title>Best PHP</title>  

        <publisher>PHPchurch</publisher>  

</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());  

    }  

}  

代碼解析:

SAXReader可以通過多種方式讀取xml資料,并傳回Document格式的對象。通過檢視源碼,可以看出read()方法接收File,InputStream和URL等格式的參數來讀取相應的xml資料。在代碼裡我示範了讀取xml文檔和xml格式的字元串兩種方式。當然,字元串要根據相應的編碼轉成輸入流才能被SAXReader讀取。

讀取到Document對象後,我們使用getRootElement()方法擷取根元素,傳回的是一個Element對象。在本例中,該元素的name即為books。

擷取根元素後,便可以一層一層的去擷取他的子元素資訊。如果知道子元素的标簽名稱,便可以直接調用element("name")方法擷取該子元素。如果不知道子元素的名稱,或者想直接擷取該元素下的全部子元素,可以調用elements()方法擷取一個包括全部元素的list,然後進行下一步的處理。

調用getName()方法擷取目前元素的元素名,attributeValue()擷取屬性名。如果目前元素沒有子元素,則調用getText()方法擷取元素值。