dom4j 提供多種途徑解析 XML 字符串,適用於不同場景。本文詳細對比 DocumentHelper.parseText (DOM)、SAXReader.read(InputSource) (SAX)、XPath 查詢三種核心用法,並演示 ID 定位、屬性提取、命名空間處理等實戰技巧。
String xml = "<request><param name='service'>single_trade_query</param></request>";
Document doc = DocumentHelper.parseText(xml);
Element root = doc.getRootElement();
// 遍歷所有子元素
for (Iterator<Element> it = root.elementIterator(); it.hasNext(); ) {
Element param = it.next();
String name = param.attributeValue("name");
String value = param.getTextTrim();
System.out.println(name + " = " + value);
}
// 獲取指定名稱子元素列表
List<Element> params = root.elements("param");
for (Element p : params) {
System.out.println(p.attributeValue("name") + ": " + p.getText());
}
String xml = "<?xml version='1.0' encoding='UTF-8'?><servlet><servlet-name>TestServlet</servlet-name></servlet>";
SAXReader reader = new SAXReader();
// 關鍵:通过 InputSource 指定編碼
InputSource source = new InputSource(new StringReader(xml));
source.setEncoding("UTF-8");
Document doc = reader.read(source);
Element root = doc.getRootElement();
for (Iterator<Element> it = root.elementIterator(); it.hasNext(); ) {
Element el = it.next();
System.out.println(el.getName() + " : " + el.getTextTrim());
}
需額外依賴 dom4j-xpath (dom4j 2.x 已內置 jaxen)。
String xml = "<request><param name='service' ID='tt'>single_trade_query</param><param name='partner'>2088001</param></request>";
Document doc = DocumentHelper.parseText(xml);
// 1. 單節點文本
String service = doc.valueOf("//param[@name='service']");
System.out.println("service = " + service); // single_trade_query
// 2. 通過 ID 定位 (注意:XML 中必須聲明 xml:id 或 DTD 指定 ID 類型,普通 id 屬性無效)
// 正確寫法: ... 或在 DTD 中声明
Element byId = doc.getNodeById("tt"); // 需 xml:id
if (byId != null) System.out.println("ID 定位: " + byId.getTextTrim());
// 3. 多節點列表
List<Node> nodes = doc.selectNodes("//param");
for (Node n : nodes) {
System.out.println(n.getName() + " [" + n.valueOf("@name") + "] = " + n.getText());
}
// 4. 條件過濾
String partner = doc.valueOf("//param[@name='partner']");
System.out.println("partner = " + partner);
Map<String, String> ns = new HashMap<>();
ns.put("ns", "https://example.com/ns");
XPath xpath = doc.createXPath("//ns:element", ns);
List<Node> list = xpath.selectNodes(doc);
element.attributeValue("attrName") 或 XPath @attrName。element.getText() 自動返回 CDATA 內容,無需特殊處理。DocumentException (解析錯誤)、InvalidXPathException (XPath 語法錯誤)。DocumentHelper;> 1MB 或高頻解析用 SAXReader 配合自定義 Handler 避免構建完整樹。| 維度 | DocumentHelper.parseText | SAXReader + InputSource | XPath (selectNodes/valueOf) |
|---|---|---|---|
| API 風格 | DOM 樹遍歷 | DOM 樹遍歷 (SAX 底層) | 聲明式查詢 |
| 編碼控制 | 自動檢測 | 可顯式指定 | 依賴底層解析器 |
| 內存佔用 | 構建完整樹 | 構建完整樹 | 構建完整樹 |
| 查詢靈活性 | 低 (手動遍歷) | 低 | 極高 (複雜路徑/條件) |
| 適用場景 | 簡單結構、一次性解析 | 需指定編碼、帶 XML 聲明 | 複雜嵌套、條件提取、批量查詢 |
dom4j 解析 XML 字符串:簡單場景用 DocumentHelper.parseText 一行搞定;需指定編碼用 SAXReader + InputSource;複雜查詢首選 XPath。記住:ID 定位需 xml:id,普通 id 屬性不生效。掌握三種方式,應對所有 XML 字符串解析需求綽綽有餘。