First Example
JXPath is a java library for Object Graph Navigation using the XPath syntax.
This requires the libraries commons-jxpath-1.3.jar, commons-beanutils.jar and commons-logging.jar to be in classpath.
The following example shows creating JXPathContext for accessing
simple POJO properties.
package com.bethecoder.tutorials.jxpath.common;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Student {
private String name;
private int age;
private String hobby;
private List<String> nickNames = new ArrayList<String> () ;
public Student () {
}
public Student ( String name, int age, String hobby ) {
super () ;
this .name = name;
this .age = age;
this .hobby = hobby;
}
public Student ( String name, int age, String hobby, String [] nickNames ) {
super () ;
this .name = name;
this .age = age;
this .hobby = hobby;
this .nickNames = Arrays.asList ( nickNames ) ;
}
public String getName () {
return name;
}
public void setName ( String name ) {
this .name = name;
}
public int getAge () {
return age;
}
public void setAge ( int age ) {
this .age = age;
}
public String getHobby () {
return hobby;
}
public void setHobby ( String hobby ) {
this .hobby = hobby;
}
public List<String> getNickNames () {
return nickNames;
}
public void setNickNames ( List<String> nickNames ) {
this .nickNames = nickNames;
}
public String toString () {
return "Student[name = " + name + ", age = " + age + ", hobby = " + hobby + ", " + nickNames + "]" ;
}
}
package com.bethecoder.tutorials.jxpath;
import org.apache.commons.jxpath.JXPathContext;
import com.bethecoder.tutorials.jxpath.common.Student;
public class BasicTest {
/**
* @param args
*/
public static void main ( String [] args ) {
Student std = new Student ( "Sriram" , 2 , "Singing" ) ;
//Create JXPathContext with Student object as root node
JXPathContext context = JXPathContext.newContext ( std ) ;
//Evaluate Xpath expression relative to root node
String name = ( String ) context.getValue ( "/name" ) ;
System.out.println ( name ) ;
String hobby = ( String ) context.getValue ( "/hobby" ) ;
System.out.println ( hobby ) ;
Integer age = ( Integer ) context.getValue ( "/age" ) ;
System.out.println ( age ) ;
}
}
It gives the following output,
Sriram
Singing
2