XML認證知識點:DOM Parser
- IBM認證
- 關注:2.12W次
DOM Document 是以層次結構組織起來的節點,或資訊片段的集合。這種層次結構允許開發者瀏覽樹來查詢特定資訊。通常,分析結構需要在完成任何工作之前裝入整個文件並且裝入層次結構。
基本的應用程式
從建立基本的應用程式,名為 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
- 文章版權屬於文章作者所有,轉載請註明 https://xuezhezhai.com/zh-tw/itrz/ibm/90k6qr.html