XML 作為經典數據交換格式,Java 提供多種解析 API。本文對比 DOM、DOM4J、JDOM、SAX 四種主流方式,附完整代碼示例與性能特點分析。
<?xml version="1.0" encoding="GB2312"?>
<RESULT>
<VALUE>
<NO>A1234</NO>
<ADDR>河南省鄭州市</ADDR>
</VALUE>
<VALUE>
<NO>B1234</NO>
<ADDR>河南省鄭州市二七區</ADDR>
</VALUE>
</RESULT>
特點:樹模型,一次性將整個文檔載入內存,隨機訪問靈活,但大文件極其消耗內存。
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("data.xml"));
NodeList nl = doc.getElementsByTagName("VALUE");
for (int i = 0; i < nl.getLength(); i++) {
String no = doc.getElementsByTagName("NO").item(i).getFirstChild().getNodeValue();
String addr = doc.getElementsByTagName("ADDR").item(i).getFirstChild().getNodeValue();
System.out.println("車牌:" + no + " 地址:" + addr);
}
特點:API 友好,支持 XPath、命名空間、可寫入 XML,內存佔用略低於 DOM,企業級首選。
SAXReader reader = new SAXReader();
Document doc = reader.read(new File("data.xml"));
Element root = doc.getRootElement();
for (Iterator i = root.elementIterator("VALUE"); i.hasNext(); ) {
Element foo = (Element) i.next();
System.out.println("車牌:" + foo.elementText("NO") + " 地址:" + foo.elementText("ADDR"));
}
// XPath 示例:List<Node> nodes = doc.selectNodes("//VALUE/NO");
特點:API 更符合 Java 集合習慣(List
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File("data.xml"));
Element root = doc.getRootElement();
List<Element> children = root.getChildren("VALUE");
for (Element child : children) {
System.out.println("車牌:" + child.getChildText("NO") + " 地址:" + child.getChildText("ADDR"));
}
特點:不載入整樹,內存佔用極低(常數級),適合超大文件;但只能順序讀寫,無法隨機訪問,編碼較繁瑣(需繼承 DefaultHandler 重寫事件方法)。
public class SaxHandler extends DefaultHandler {
private Stack<String> tags = new Stack<>();
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs) {
tags.push(qName);
}
@Override
public void characters(char[] ch, int start, int length) {
String tag = tags.peek();
if ("NO".equals(tag)) System.out.print("車牌:" + new String(ch, start, length));
if ("ADDR".equals(tag)) System.out.println(" 地址:" + new String(ch, start, length));
}
}
// 使用
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sp = sf.newSAXParser();
sp.parse(new File("data.xml"), new SaxHandler());
| 維度 | DOM | DOM4J | JDOM | SAX |
|---|---|---|---|---|
| 內存佔用 | 高(全樹載入) | 中 | 中 | 極低(流式) |
| 訪問模式 | 隨機 | 隨機 + XPath | 隨機 | 順序只讀 |
| 寫入/修改 XML | 支持 | 最強 | 支持 | 不支持 |
| 學習曲線 | 中 | 低 | 低 | 高(事件模型) |
| 依賴 | 無 (JDK) | dom4j.jar | jdom.jar | 無 (JDK) |
| 適用場景 | 小文件、需隨機修改 | 企業級通用首選 | 教學、輕量項目 | 超大文件、只讀、內存受限 |
現代項目中,JSON 已大幅替代 XML;若必須處理 XML,DOM4J 仍是生產環境最穩妥選擇。