Apache Commons JXPath 是 XPath 的 Java 實現,提供統一 API 以 XPath 語法訪問 JavaBeans、集合、Map、動態屬性對象(如 ServletContext)甚至 XML 文檔,並支援擴展機制適配其他對象模型。
commons-jxpath-1.1.jarCompany company = new Company();
company.setId(1); company.setName("vivianj組織"); company.setAddress("www.vivianj.org");
JXPathContext context = JXPathContext.newContext(company);
String name = (String) context.getValue("name"); // "vivianj組織"
Integer id = (Integer) context.getValue("id"); // 1
Lenient 模式:context.setLenient(true) 讓不存在屬性返回 null 而非拋異常。
Association assoc = new Association();
assoc.setCompany(company);
JXPathContext ctx = JXPathContext.newContext(assoc);
ctx.setLenient(true);
String name = (String) ctx.getValue("company/name"); // 穿透訪問
下標從 1 開始(XPath 慣例)。
// 訪問第 5 個元素的 name
String name = (String) ctx.getValue("companysInArray[5]/name");
// 批量獲取:position() > 3
Iterator it = ctx.iterate("companysInArray[position() > 3]");
// 條件篩選:name='name3'
Iterator it = ctx.iterate("companysInArray[name='name3']");
MyMapSource source = new MyMapSource(); // 內含 Map<String,Object>
JXPathContext ctx = JXPathContext.newContext(source);
Integer id = (Integer) ctx.getValue("mapSource/id"); // 獲取 Map 中 key=id 的值
// XML 綁定到 Container
URL url = getClass().getResource("companys.xml");
Container container = new DocumentContainer(url);
JXPathContext ctx = JXPathContext.newContext(container);
// 訪問元素
String street = (String) ctx.getValue("companys/company[@id='101']/address/street");
// 訪問屬性(需 @ 符號)
String id = (String) ctx.getValue("companys/company[@id='101']/@id");
JXPath 以 XPath 為統一查詢語言,打通 Java 對象圖、集合、Map、XML 等異構數據源,代碼簡潔直觀,極適合動態數據訪問場景。功能遠不止文中示範,歡迎深入探索。