- 相關(guān)推薦
XML認證知識點(diǎn):DOM Parser
DOM Document 是以層次結構組織起來(lái)的節點(diǎn),或信息片段的集合。這種層次結構允許開(kāi)發(fā)者瀏覽樹(shù)來(lái)查找特定信息。通常,分析結構需要在完成任何工作之前裝入整個(gè)文檔并且裝入層次結構。

基本的應用程序
從創(chuàng )建基本的應用程序,名為 OrderProcessor 的類(lèi)開(kāi)始。
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import org.w3c.dom.Document;
public class OrderProcessor {
public static void main (String args[]) {
File docFile = new File("orders.xml");
Document doc = null;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(docFile);
} catch (Exception e) {
System.out.print("Problem parsing the file.");
}
}
}
首先,Java 導入必要的類(lèi),然后創(chuàng )建 OrderProcessor 應用程序。在本教程中的這個(gè)示例將只處理一個(gè)文件,所以為簡(jiǎn)短起見(jiàn),該應用程序包含對它的直接引用。
應用程序在 try-catch 塊外部定義了 Document 對象,以便在后面使用該對象。try-catch 使您能執行可能會(huì )拋出異常的一些操作,這樣不會(huì )危及整個(gè)應用程序。如果異常拋出,則應用程序簡(jiǎn)單地執行相應的 catch 代碼。
在 try-catch 塊內部,應用程序創(chuàng )建 DocumentBuilderFactory,然后使用它來(lái)創(chuàng )建 DocumentBuilder。最后,DocumentBuilder 解析該文件以創(chuàng )建 Document。
編輯文檔
更改節點(diǎn)數據
Node.setNodeValue(elemValue);
添加節點(diǎn)
String totalString = new Double(total).toString();
Node totalNode = doc.createTextNode(totalString);
//Document 對象創(chuàng )建新的文本節點(diǎn),該節點(diǎn)帶有作為值的 totalString
Element totalElement = doc.createElement("total");
//創(chuàng )建新元素 total
totalElement.appendChild(totalNode);
// 將節點(diǎn)添加到新的 total 元素。
thisOrder.insertBefore(totalElement, thisOrder.getFirstChild());
//將新元素添加到 Document,指定新的 Node,然后指定新 Node 在 Node 之前
除去節點(diǎn)
Node deadNode = thisOrderItem.getParentNode().removeChild(thisOrderItem);
替換節點(diǎn)
Element backElement = doc.createElement("backordered");
//創(chuàng )建新元素 backordered
Node deadNode = thisOrderItem.getParentNode().replaceChild(backElement,thisOrderItem);
創(chuàng )建和設置屬性
Element backElement = doc.createElement("backordered");
//創(chuàng )建新元素 backordered
backElement.setAttributeNode(doc.createAttribute("itemid"));
//創(chuàng )建新屬性 itemid
String itemIdString = thisOrderItem.getAttributeNode("itemid").getNodeValue();
//取得thisOrderItem的屬性itemid的值
backElement.setAttribute("itemid", itemIdString);
//設置backElement的屬性item的值,可以省略createAttribute
Node deadNode = thisOrderItem.getParentNode().replaceChild(backElement,thisOrderItem);
除去屬性
Element thisOrder = (Element)orders.item(orderNum);
Element customer = (Element)thisOrder.getElementsByTagName("cusomertid").item(0);
customer.removeAttribute("limit");
//去除屬性limit
【XML認證知識點(diǎn):DOM Parser】相關(guān)文章:
XML認證元素類(lèi)型聲明05-28
關(guān)于IBM XML認證考試的要點(diǎn)09-07
ibm認證考試知識點(diǎn)08-05
Linux認證考試必考知識點(diǎn)09-02
關(guān)于HTML DOM的簡(jiǎn)介10-16
關(guān)于XML的介紹08-29
Xml的英語(yǔ)解釋11-01