tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Tools and Libs > JXPath > How to Access Indexed Properties

How to Access Indexed Properties 

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 accessing indexed properties in JXPath.

File Name  :  
com/bethecoder/tutorials/jxpath/common/ComplexBean.java 
   
package com.bethecoder.tutorials.jxpath.common;

import java.util.List;

public class ComplexBean {

  private List<String> stringList;
  private String [] stringArray;
  
  public List<String> getStringList() {
    return stringList;
  }
  public void setStringList(List<String> stringList) {
    this.stringList = stringList;
  }
  public String[] getStringArray() {
    return stringArray;
  }
  public void setStringArray(String[] stringArray) {
    this.stringArray = stringArray;
  }

}
   

File Name  :  
com/bethecoder/tutorials/jxpath/IndexedPropertiesTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.jxpath;

import java.util.Arrays;
import java.util.List;

import org.apache.commons.jxpath.JXPathContext;

import com.bethecoder.tutorials.jxpath.common.ComplexBean;

public class IndexedPropertiesTest {

  /**
   @param args
   */
  public static void main(String[] args) {
    ComplexBean bean = new ComplexBean();
    bean.setStringArray(new String [] { "Maths""Physics""Chemistry""Hindi""English"});
    bean.setStringList(Arrays.asList("Maths""Physics""Chemistry""Hindi""English"));

    //Create JXPathContext with ComplexBean instance as ROOT node
      JXPathContext context = JXPathContext.newContext(bean);
      
      List<String> stringList = (List<String>context.getValue("/stringList");
      System.out.println(stringList);
      
      //According to the W3C standard index starts from 1 not ZERO 
      System.out.println(context.getValue("/stringList[1]"));
      System.out.println(context.getValue("/stringList[2]"))
      System.out.println(context.getValue("/stringList[3]"))
      
      String [] stringArray = (String []) context.getValue("/stringArray");
      System.out.println(Arrays.toString(stringArray));
      
      //According to the W3C standard index starts from 1 not ZERO 
      System.out.println(context.getValue("/stringArray[1]"));
      System.out.println(context.getValue("/stringArray[2]"))
      System.out.println(context.getValue("/stringArray[3]"))
  }

}
   

It gives the following output,
[Maths, Physics, Chemistry, Hindi, English]
Maths
Physics
Chemistry

[Maths, Physics, Chemistry, Hindi, English]
Maths
Physics
Chemistry



 
  


  
bl  br