化一个Company对象
Company company = new Company();
//设置该对象的各个属性
company.setId(1);
company.setName("vivianj组织");
company.setAddress("www.vivianj.org");
//初始化JXPath的上下文环境
JXPathContext context = JXPathContext.newContext(company);
//通知系统使用Lenient 访问模式
context.setLenient(true);
//使用XPath语法来访问该对象的属性
String name1 = (String)context.getValue("name1");
System.out.println("name1: " + name1);
}
}
[注] name1 不是Company类的属性,但是由于使用了Lenient 访问模式,所以系统返回null。
Jakarta-Common-JXPath使用笔记(3)
时间:2011-01-28 csdn博客 沈斌
C.多种访问方式,新建Association类如下:
package demo.bean;
import java.util.ArrayList;
import java.util.Collection;
public class Association ...{
private Company company;
public Company getCompany() ...{
return this.company;
}
public void setCompany(Company p_company) ...{
this.company = p_company;
}
public Company[] getCompanysInArray() ...{
Company[] companysInArray = new Company[5];
for (int i = 0; i < 5; i++) ...{
//实例化新的Company对象
Company comp = new Company();
comp.setId(i);
comp.setName("Name" + i);
comp.setAddress("address" + i);
//将实例化的对象赋值给到数组的对应元素
companysInArray[i] = comp;
}
return companysInArray;
}
public Collection<Company> getCompanysInCollection() ...{
ArrayList<Company> companysInCollection = new ArrayList<Company>();
for (int i = 0; i < 5; i++) ...{
//实例化新的Company对象
Company comp = new Company();
comp.setId(i);
comp.setName("Name" + i);
comp.setAddress("address" + i);
//将实例化的对象增加到Collection中
companysInCollection.add(comp);
}
return companysInCollection;
}
}
测试代码:
package demo;
import java.util.Iterator;
import org.apache.commons.jxpath.JXPathContext;
import demo.bean.Association;
import demo.bean.Company;
public class AssociationDemo ...{
/**//*
public static void main(String[] args) {
//实例化Association类
Association association = new Association();
//实例化Company类
Company company = new Company();
company.setId(1);
company.setName("vivianj组织");
company.setAddress("www.vivianj.org");
//设置Association对象的company属性
association.setCompany(company);
//初始化JXPath上下文
JXPathContext context = JXPathContext.newContext(association);
//使用Lenient访问模式访问嵌套属性
context.setLenient(true);
//通过JXPath方法获得
|