簡述 DOM 概念與邏輯結構,實例講解 DOM 文件操作與 XML 檔案互轉的 Java 實作。
W3C 2000/11/13 發布 DOM Level 2。文件物件模型為 HTML/XML 程式介面規範,跨平台跨語言。定義文件在記憶體中的邏輯結構(節點樹),提供存取操作方法。利用 DOM 可實現 DOM⇄XML 互轉、遍歷操作內容。
節點樹表達。解析 XML 將元素轉為節點物件。節點類型:Document(根節點,唯一)、Element、Comment、Text 等。格式良好的 XML 每個元素對應一個節點。透過 DOM 介面轉換後可自由處理 XML。
org.w3c.dom:Document、DocumentType、Node、NodeList、Element、Text 等核心介面javax.xml.parsers:DocumentBuilderFactory、DocumentBuilder 解析 XML 生成 DOMjavax.xml.transform.dom/stream:DOMSource、StreamResult 將 DOM 輸出為 XML/文字/HTMLDocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File(fileName));
Element root = document.getDocumentElement();
NodeList list = root.getChildNodes();
getElement(list); // 遞迴處理
void getElement(NodeList nl) {
if (nl.getLength() == 0) return;
for (int i=0; i<nl.getLength(); i++) {
Node n = nl.item(i);
short type = n.getNodeType();
if (type == Node.ELEMENT_NODE) {
System.out.println("Element: " + n.getNodeName());
getElement(n.getChildNodes());
} else if (type == Node.TEXT_NODE) {
System.out.println("Text: " + n.getNodeValue().trim());
}
}
}
Element root = document.getDocumentElement();
Element booktype = document.createElement("COMPUTES");
root.appendChild(booktype);
Element booktitle = document.createElement("Title");
booktype.appendChild(booktitle);
Text bookname = document.createTextNode("understand Corba");
booktitle.appendChild(bookname);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File("text.xml"));
transformer.transform(source, result);
完整程式在 Windows 2000 + JDK 1.4 驗證通過。操作遵循 DOM 標準,適用其他語言。