DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> XML學習教程 >> XML詳解
用 dom4j 輕鬆處理 Java 中的 XML 文件
編輯:XML詳解     

dom4j 是 Java 平台上簡單易用的 XML 處理工具。它建構在 Java Collections 架構之上,並對 DOM、SAX 與 JAXP 提供完整支援。以下五個操作涵蓋了日常九成以上的需求。

一、建立新的 XML 文件

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class Users {

    public Document createDocument() {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("users");

        root.addElement("user")
            .addAttribute("userid", "sucode")
            .addAttribute("username", "Eric Yu")
            .addText("myself");

        root.addElement("user")
            .addAttribute("userid", "scottl")
            .addAttribute("username", "Scott Long")
            .addText("FreeBSD leader");

        return document;
    }
}

上述程式碼產生的文件如下:

<users>
  <user userid="sucode" username="Eric Yu">myself</user>
  <user userid="scottl" username="Scott Long">FreeBSD leader</user>
</users>

addElement 與 addAttribute 都回傳元素本身,因此可以一路串接下去,程式碼比 DOM 簡潔不少。

二、XML 文件與字串互相轉換

dom4j 有個很方便的特性:能非常直覺地把文件轉成 XML 格式的字串。因為 Document、Element、Attribute 都繼承了 Node 介面,所以全都提供 asXML() 方法,回傳該節點的 XML 描述。

Document document = new Users().createDocument();
String text = document.asXML();

反向操作同樣簡單:

Document doc = DocumentHelper.parseText(text);

三、快速遍歷

處理大型 XML 文件時,為每個迴圈建立一個 Iterator 物件會帶來可觀的額外負擔。這時建議改用「快速遍歷」(fast looping),直接以索引存取節點:

public void treeWalk(Document document) {
    treeWalk(document.getRootElement());
}

public void treeWalk(Element element) {
    for (int i = 0, size = element.nodeCount(); i < size; i++) {
        Node node = element.node(i);
        if (node instanceof Element) {
            treeWalk((Element) node);
        } else {
            // 這裡放你的業務邏輯
        }
    }
}

注意這裡把 nodeCount() 的結果先存進區域變數,避免每次迴圈都重新呼叫一次。

四、使用 XPath

在 dom4j 中,XPath 可以作用在文件或任何節點上,這是它比原生 DOM 好用的地方之一。

// 傳回 users 底下的所有 user 節點
List userList = document.selectNodes("//users/user");

// 傳回 userid 為 sucode 的那個 user 節點
Element me = (Element) document.selectSingleNode("//users/user[@userid='sucode']");

selectSingleNode 只回傳符合條件的第一個節點;若有多個節點匹配,其餘會被忽略。

五、把 XML 文件寫入檔案

最簡單的方式是直接用 write:

FileWriter out = new FileWriter("users.xml");
document.write(out);

如果需要控制輸出的格式(例如要不要縮排、要不要 XML 宣告),改用 XMLWriter 搭配 OutputFormat:

import java.io.FileWriter;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class DOMTest {

    public void write(Document document) throws IOException {
        // 建立 XMLWriter,目標檔案 users.xml,使用美化列印格式
        XMLWriter writer = new XMLWriter(
            new FileWriter("users.xml"),
            OutputFormat.createPrettyPrint());

        writer.write(document);
        writer.close();
    }
}

OutputFormat 除了 createPrettyPrint(),還可以透過 setEncoding("UTF-8") 指定編碼、setSuppressDeclaration(true) 隱藏 XML 宣告,處理中文時建議明確指定 UTF-8,避免受平台預設編碼影響。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved