JXPath 是 Apache 提供的 XPath 在 Java 中的實現,屬於 Jakarta Commons 組件。它允許開發者使用標準 XPath 語法,統一訪問 JavaBean、集合、Map、數組甚至 XML 文檔等異構數據結構。最新版本 1.1 可從 官網 下載。
所有操作的入口是 JXPathContext,它綁定一個根對象(Context Bean),隨後通過 getValue()、setValue()、iterate() 等方法按 XPath 表達式導航對象圖。
// 領域對象
Company company = new Company();
company.setId(1);
company.setName("vivianj組織");
company.setAddress("www.vivianj.org");
// 建立上下文
JXPathContext context = JXPathContext.newContext(company);
// 直接用屬性名作為 XPath
String name = (String) context.getValue("name"); // "vivianj組織"
Integer id = (Integer) context.getValue("id"); // 1
String address = (String) context.getValue("address"); // "www.vivianj.org"
默認情況下,訪問不存在的屬性會拋異常。啟用寬容模式後返回 null:
context.setLenient(true);
String name1 = (String) context.getValue("name1"); // 不存在,返回 null,不拋異常
定義關聯對象 Association,包含單一 Company、Company 數組、Company 集合。
Association assoc = new Association();
JXPathContext ctx = JXPathContext.newContext(assoc);
ctx.setLenient(true);
// 1. 訪問巢狀屬性
String name = (String) ctx.getValue("company/name");
// 2. 訪問數組/集合指定索引元素
String arrName = (String) ctx.getValue("companysInArray[5]/name"); // 數組第 5 個(下標 4)
String collName = (String) ctx.getValue("companysInCollection[5]/name"); // 集合第 5 個
// 3. 迭代並過濾:position() > 3
Iterator<?> itArr = ctx.iterate("companysInArray[position() > 3]");
while (itArr.hasNext()) {
Company c = (Company) itArr.next();
System.out.println(c.getAddress());
}
// 4. 條件過濾:name='Name3'
Iterator<?> itArr2 = ctx.iterate("companysInArray[name='Name3']");
while (itArr2.hasNext()) {
Company c = (Company) itArr2.next();
System.out.println(c.getName());
}
// 5. 取集合最後一個元素
Iterator<?> itColl = ctx.iterate("companysInCollection[last()]");
MyMapSource mapSrc = new MyMapSource(); // 內部有 Map<String,Object> mapSource
JXPathContext ctx = JXPathContext.newContext(mapSrc);
Integer id = (Integer) ctx.getValue("mapSource/id"); // 訪問 Map 的 key
通過 DocumentContainer 封裝 XML 資源:
Companys companys = new Companys(); // 內部 getCompanys() 返回 DocumentContainer
JXPathContext ctx = JXPathContext.newContext(companys);
// XML 結構:sun ... ...
// 訪問街道
String street = (String) ctx.getValue("companys/companys/company[@id='101']/address/street");
// 訪問屬性
String id = ctx.getValue("companys/companys/company[@id='101']/@id");
// 條件查找子元素
String name = ctx.getValue("companys/companys/company[name='sun']/name");
JXPath 以 XPath 為統一查詢語言,打通了 Java 對象圖與 XML 的訪問壁壘,特別適合動態屬性訪問、配置解析、測試驗證等場景。善用 iterate() 與 XPath 謂詞(位置、條件)可大幅減少手動遍歷代碼。