XML認證知識點:DOM Parser

DOM Document 是以層次結構組織起來的節點,或信息片段的集合。這種層次結構允許開發者瀏覽樹來查找特定信息。通常,分析結構需要在完成任何工作之前裝入整個文檔並且裝入層次結構。

XML認證知識點:DOM Parser

  基本的應用程序

從創建基本的應用程序,名爲 OrderProcessor 的類開始。

import mentBuilder;

import mentBuilderFactory;

import ;

import ment;

public class OrderProcessor {

public static void main (String args[]) {

File docFile = new File("");

Document doc = null;

try {

DocumentBuilderFactory dbf = nstance();

DocumentBuilder db = ocumentBuilder();

doc = e(docFile);

} catch (Exception e) {

t("Problem parsing the file.");

}

}

}

首先,Java 導入必要的類,然後創建 OrderProcessor 應用程序。在本教程中的這個示例將只處理一個文件,所以爲簡短起見,該應用程序包含對它的直接引用。

應用程序在 try-catch 塊外部定義了 Document 對象,以便在後面使用該對象。try-catch 使您能執行可能會拋出異常的一些操作,這樣不會危及整個應用程序。如果異常拋出,則應用程序簡單地執行相應的. catch 代碼

在 try-catch 塊內部,應用程序創建 DocumentBuilderFactory,然後使用它來創建 DocumentBuilder。最後,DocumentBuilder 解析該文件以創建 Document。

  編輯文檔

更改節點數據

odeValue(elemValue);

添加節點

String totalString = new Double(total)ring();

Node totalNode = teTextNode(totalString);

//Document 對象創建新的文本節點,該節點帶有作爲值的 totalString

Element totalElement = teElement("total");

//創建新元素 total

ndChild(totalNode);

// 將節點添加到新的 total 元素。

rtBefore(totalElement, irstChild());

//將新元素添加到 Document,指定新的 Node,然後指定新 Node 在 Node 之前

除去節點

Node deadNode = arentNode()veChild(thisOrderItem);

替換節點

Element backElement = teElement("backordered");

//創建新元素 backordered

Node deadNode = arentNode()aceChild(backElement,thisOrderItem);

創建和設置屬性

Element backElement = teElement("backordered");

//創建新元素 backordered

ttributeNode(teAttribute("itemid"));

//創建新屬性 itemid

String itemIdString = ttributeNode("itemid")odeValue();

//取得thisOrderItem的屬性itemid的值

ttribute("itemid", itemIdString);

//設置backElement的屬性item的值,可以省略createAttribute

Node deadNode = arentNode()aceChild(backElement,thisOrderItem);

除去屬性

Element thisOrder = (Element)(orderNum);

Element customer = (Element)lementsByTagName("cusomertid")(0);

veAttribute("limit");

//去除屬性limit