JXPath是apache组织提供的XPath的java实现,属于jakarta的一部分,最新的版本是1.1,JXPath的主要功能在于一组java类库来使用XPath的方式访问符合JavaBeans规范的java类、java集合(Collections)、其他具有动态属性的对象(如Map、ServletContext等),同时提供了一套扩展机制使我们可以增加对这些对象之外的其他对象模型的支持
public class Person { private String name; private String password; public Person() { super(); } public Person(String name, String password) { super(); this.name = name; this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
public class Companys { private Container companys = null; private Person person; public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public Companys() { person = new Person("pan", "123456"); } public Container getCompanys() { if (companys == null) { URL url = getClass().getResource("test.xml"); companys = new DocumentContainer(url); } return companys; } }
test.xml
<?xml version="1.0" encoding="UTF-8"?> <companys> <company id="101"> <name>sun</name> <address> <street>18 #,WenShan Road</street> </address> </company> <company id="102"> <name>ibm</name> <address> <street>18 #,WenEr Road</street> </address> </company> </companys>
public class TestJXPath { /** * @param args */ public static void main(String[] args) { Companys comp = new Companys(); JXPathContext context = JXPathContext.newContext(comp); System.out.println(context.getValue( "companys/companys/company[@id = '101']/address/street", String.class)); System.out.println(context.getValue("person/name")); Map<String, Person> map = new HashMap<String, Person>(); map.put("p1", new Person("pajifeng", "12544456")); context = JXPathContext.newContext(map); System.out.println(context.getValue("p1/name")); } }
结果:
18 #,WenShan Road
pa
pajifeng