XML(可擴展標記語言)作為數據交換的標準格式,在 Java 開發中極為常見。本文將詳細介紹如何使用 Java 內建的 DOM(Document Object Model)解析器來讀取與解析 XML 文件,並提供完整的代碼範例供參考。
假設我們有一個 students.xml 文件,內容如下:
<?xml version="1.0"?>
<students>
<student>
<name>John</name>
<grade>B</grade>
<age>12</age>
</student>
<student>
<name>Mary</name>
<grade>A</grade>
<age>11</age>
</student>
<student>
<name>Simon</name>
<grade>A</grade>
<age>18</age>
</student>
</students>
以下代碼展示了如何使用 DocumentBuilderFactory 與 DocumentBuilder 解析 XML,並遍歷所有學生節點:
package net.viralpatel.java.xmlparser;
import java.io.File;
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 XMLParser {
public void getAllUserNames(String fileName) {
try {
// 1. 獲取 DocumentBuilderFactory 實例
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// 2. 創建 DocumentBuilder
DocumentBuilder db = dbf.newDocumentBuilder();
// 3. 載入 XML 文件
File file = new File(fileName);
if (file.exists()) {
Document doc = db.parse(file);
// 4. 獲取根元素
Element docEle = doc.getDocumentElement();
System.out.println("根元素: " + docEle.getNodeName());
// 5. 獲取所有 student 節點
NodeList studentList = docEle.getElementsByTagName("student");
System.out.println("學生總數: " + studentList.getLength());
// 6. 遍歷並提取數據
if (studentList != null && studentList.getLength() > 0) {
for (int i = 0; i < studentList.getLength(); i++) {
Node node = studentList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
System.out.println("=====================");
Element e = (Element) node;
// 獲取子元素值
NodeList nameList = e.getElementsByTagName("name");
System.out.println("姓名: " + nameList.item(0).getChildNodes().item(0).getNodeValue());
NodeList gradeList = e.getElementsByTagName("grade");
System.out.println("年級: " + gradeList.item(0).getChildNodes().item(0).getNodeValue());
NodeList ageList = e.getElementsByTagName("age");
System.out.println("年齡: " + ageList.item(0).getChildNodes().item(0).getNodeValue());
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
XMLParser parser = new XMLParser();
parser.getAllUserNames("c:\\test.xml");
}
}
DocumentBuilderFactory.newInstance() 用於獲取工廠實例。dbf.newDocumentBuilder() 生成解析器。db.parse(file) 將 XML 文件轉為 Document 對象樹。getElementsByTagName 獲取節點列表,再通過 getChildNodes().item(0).getNodeValue() 取得文本內容。SAXParseException。dbf.setNamespaceAware(true))以應對複雜 XML。本文通過完整實例演示了 Java DOM 解析 XML 的標準流程。掌握此技術有助於處理配置文件、數據交換等常見場景。如需更高性能,可進一步學習 SAX 或 StAX 解析器。