Jakarta-Common-JXPath使用笔记
时间:2011-01-28 csdn博客 沈斌
JXPath是apache公司提供的XPath的java实现,属于jakarta的一部分,最新的版本是1.1,JXPath的主要功能在于一组java类库来使用XPath的方式访问符合JavaBeans规范的java类、java集合(Collections)、其他具有动态属性的对象(如Map、ServletContext等),同时提供了一套扩展机制使我们可以增加对这些对象之外的其他对象模型的支持。
下载地址:http://commons.apache.org/jxpath/
A.访问JavaBean的属性
package demo.bean;
import java.util.Comparator;
public class Company implements Comparator<Object>...{
private String name = "";
private int id = 0;
private String address = "";
public void setName(String p_name)...{
this.name = p_name;
}
public void setId(int p_id)...{
this.id = p_id;
}
public void setAddress(String p_address)...{
this.address = p_address;
}
public String getName()...{
return this.name;
}
public int getId()...{
return this.id;
}
public String getAddress()...{
return this.address;
}
public int compare(Object o1, Object o2)...{
return 0;
}
public boolean equals(Object obj) ...{
boolean result = false;
if (obj instanceof Company)...{
Company company = (Company) obj;
if (company.getId()==this.id && company.getName().equals(this.getName())
&& company.getAddress().equals(this.getAddress()))
result = true;
}
return result;
}
}
Jakarta-Common-JXPath使用笔记(2)
时间:2011-01-28 csdn博客 沈斌
测试代码:
package demo;
import org.apache.commons.jxpath.JXPathContext;
import demo.bean.Company;
public class JxPathDemo ...{
public static void main(String[] args) ...{
//实例化一个Company对象
Company company = new Company();
//设置该对象的各个属性
company.setId(1);
company.setName("vivianj组织");
company.setAddress("www.vivianj.org");
//初始化JXPath的上下文环境
JXPathContext context = JXPathContext.newContext(company);
//使用XPath语法来访问该对象的属性
//getValue方法的参数"name"、"id"、"address"使用了XPath的语法,
//他们分别代表要访问company对象的属性name、id、address
String name = (String)context.getValue("name");
Integer id = (Integer) context.getValue("id");
String address = (String)context.getValue("address");
System.out.println("name: " + name);
System.out.println("id: " + id);
System.out.println("address: " + address);
}
}
B.Lenient 访问模式
package demo;
import org.apache.commons.jxpath.JXPathContext;
import demo.bean.Company;
public class LenientDemo ...{
public static void main(String[] args) ...{
//实例
|