DocumentBuilderFactory.newInstance() → 取得工廠factory.newDocumentBuilder() → 取得解析器builder.parse(InputStream) → 解析 XML 產生 Documentdoc.getDocumentElement() → 取得根元素element.getChildNodes() → 取得子節點列表Node.ELEMENT_NODE、讀取屬性、文字內容package com.st.demo;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XmlReader {
public static void main(String[] args) {
new XmlReader().parse("D:/test1.xml");
}
public void parse(String xmlPath) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// 建議開啟命名空間感知,避免同名標籤衝突
factory.setNamespaceAware(true);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream is = new FileInputStream(new File(xmlPath));
Document doc = builder.parse(is);
Element root = doc.getDocumentElement();
NodeList books = root.getChildNodes();
if (books != null) {
for (int i = 0; i < books.getLength(); i++) {
Node book = books.item(i);
if (book.getNodeType() == Node.ELEMENT_NODE) {
// 7. 讀取屬性
String email = ((Element) book).getAttribute("email");
System.out.println("Email: " + email);
// 8. 遍歷子元素
NodeList children = book.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
Node child = children.item(j);
if (child.getNodeType() == Node.ELEMENT_NODE) {
String tagName = child.getNodeName();
// 文字內容在第一個 TEXT_NODE 子節點
String text = child.getTextContent().trim();
if ("name".equals(tagName)) {
System.out.println(" Name: " + text);
} else if ("price".equals(tagName)) {
System.out.println(" Price: " + text);
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 需求 | 方法 | 備註 |
|---|---|---|
| 取得屬性值 | element.getAttribute("name") | 屬性非子節點,直接用 Element 介面 |
| 取得文字內容 | node.getTextContent() | 遞迴取得所有子文字,含換行;若只要直接文字用 node.getFirstChild().getNodeValue() |
| 判斷節點型別 | node.getNodeType() == Node.ELEMENT_NODE | 常見型別:ELEMENT_NODE(1), ATTRIBUTE_NODE(2), TEXT_NODE(3) |
| 取得子元素(僅元素) | element.getElementsByTagName("name") | 遞迴搜尋;若只要直接子元素需自行過濾 |
TEXT_NODE(含換行空白),遍歷時必須檢查 node.getNodeType()。xmlns,需 factory.setNamespaceAware(true) 並使用 getAttributeNS() 或 XPath。parse(InputStream) 會自動偵測 XML 宣告的 encoding;若無宣告預設 UTF-8。若只需抽取特定資料,XPath 更簡潔:
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList prices = (NodeList) xpath.evaluate("//book/price", doc, XPathConstants.NODESET);
for (int i = 0; i < prices.getLength(); i++) {
System.out.println(prices.item(i).getTextContent());
}
XPath 適用「查詢導向」場景;DOM 適用「全樹操作/修改」場景。