| 類/接口 | 作用 |
|---|---|
| DocumentBuilderFactory | 工廠模式獲取解析器實例 |
| DocumentBuilder | 將 XML 文件/流解析為 Document 對象 |
| Document | DOM 樹根節點,代表整個文檔 |
| Element | 元素節點,可獲取屬性、子節點 |
| Node/NodeList | 通用節點接口與節點列表 |
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.File;
public class XmlDomParserDemo {
public static void main(String[] args) throws Exception {
// 1. 獲取工廠與構建器
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// 可選:啟用命名空間感知、驗證、忽略註釋等
// factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
// 2. 解析文件生成 Document
File xmlFile = new File("test.xml");
Document doc = builder.parse(xmlFile);
// 3. 獲取根元素
Element root = doc.getDocumentElement();
System.out.println("根元素: " + root.getNodeName()); // Accounts
// 4. 遍歷子節點
NodeList accounts = root.getChildNodes();
for (int i = 0; i < accounts.getLength(); i++) {
Node node = accounts.item(i);
// 過濾文本節點(換行、縮進產生的 #text)
if (node.getNodeType() != Node.ELEMENT_NODE) continue;
Element account = (Element) node;
String type = account.getAttribute("type");
System.out.println("\n找到賬號,類型: " + type);
// 5. 解析子元素
NodeList fields = account.getChildNodes();
for (int j = 0; j < fields.getLength(); j++) {
Node field = fields.item(j);
if (field.getNodeType() != Node.ELEMENT_NODE) continue;
String tagName = field.getNodeName();
String text = field.getTextContent().trim();
switch (tagName) {
case "code": System.out.println("卡號: " + text); break;
case "pass": System.out.println("密碼: " + text); break;
case "name": System.out.println("姓名: " + text); break;
case "money": System.out.println("餘額: " + text); break;
}
}
}
}
}
<?xml version="1.0" encoding="GBK"?>
<Accounts>
<Account type="type1">
<code>100001</code>
<pass>123</pass>
<name>李四</name>
<money>1000000.00</money>
</Account>
<Account type="type2">
<code>100002</code>
<pass>123</pass>
<name>張三</name>
<money>1000.00</money>
</Account>
</Accounts>
根元素: Accounts 找到賬號,類型: type1 卡號: 100001 密碼: 123 姓名: 李四 餘額: 1000000.00 找到賬號,類型: type2 卡號: 100002 密碼: 123 姓名: 張三 餘額: 1000.00
xmlns,需 factory.setNamespaceAware(true) 並使用 getElementsByTagNameNS()factory.setFeature("https://apache.org/xml/features/disallow-doctype-decl", true)XPathFactory.newInstance().newXPath().compile("//Account[@type='type1']/code/text()").evaluate(doc)DOM 解析以 直觀的樹操作 見長,適合中小型 XML 配置文件、報文解析。掌握 DocumentBuilderFactory → DocumentBuilder → Document → Element/NodeList 核心鏈路,配合節點類型過濾 (Node.ELEMENT_NODE) 與 getTextContent(),即可高效完成 90% 的 XML 讀取需求。大文件、高併發場景請果斷切換至 StAX/SAX。