Welcome 微信登录

首页 / 软件开发 / JAVA / jxpath学习笔记

jxpath学习笔记2011-01-29 blogjava Skynetget set 参考 BeanUtil 包 和 Xpath

http://commons.apache.org/ 的 jxpath User"s Guide

类的加载

JXPathContext context=JXPathContext.newContext( obj );
//和 xpath 的 范围确定

一般取值 存值

String fName=(String)context.getValue("firstName"); //setValue
//参考 http://www.blogjava.net/Good-Game/archive/2007/08/10/135739.html

一般的统计和使用 c 为 list [id,name,.....]

JXPathContext context = JXPathContext.newContext(c);
System.out.println( context.getValue("count( .[name="oo" and id="1" ] )") ); //对象 name=oo 和 id=1的有多少个
System.out.println( context.getValue("sum( .[name="oo" and id="1" ]/id )") );//对象name=oo和id=1的所有id相加
得到集合

Iterator threeBooks=context.iterate("books[position()<4]");
//xpath 的位置函数 position 其他函数参考 http://www.w3.org/TR/xpath
//4 Core Function Library

xpath 使用

public class Employee {
private Map addressMap = new HashMap();
{addressMap.put("home", new Address(...));
addressMap.put("office", new Address(...));
}
public Map getAddresses(){
return addressMap;
}
...
}
String homeZipCode = (String)context. getValue("addresses[@name="home"]/zipCode");
//使用的是 addressMap map 的 key = home 的Address类属性的 zipCode
xml 在程序 与 xpath 的切入点

<?xml version="1.0" ?>
<vendor>
<location id="store101">
<address>
<street>Orchard Road</street>
</address></location><location id="store102"><address><street>Tangerine Drive</street></address></location></vendor>
class Company {private Container locations = null;public Container getLocations(){if (locations == null){URL url = getClass().getResource("Vendor.xml");locations = new XMLDocumentContainer(url);}return locations;}
}...context = JXPathContext.newContext(new Company());
...String street = (String)context.getValue("locations/vendor/location[@id = "store102"]//street");
// 类Container的 属性 locations 头 vendor(xml内) .....