tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 Tools and Libs > JXPath > First Example

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.

File Name  :  
com/bethecoder/tutorials/jxpath/common/Student.java 
   
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 + "]";
  }

}
   

File Name  :  
com/bethecoder/tutorials/jxpath/BasicTest.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
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 = (Stringcontext.getValue("/name");
    System.out.println(name);
    
    String hobby = (Stringcontext.getValue("/hobby");
    System.out.println(hobby);
    
    Integer age = (Integercontext.getValue("/age");
    System.out.println(age);
  }

}
   

It gives the following output,
Sriram
Singing
2


                    Print

   



Books Recommendation

 
 
bl  br