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

Last Function 

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 using last function 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/LastFunctionTest.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 LastFunctionTest {

  /**
   @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);
      
      //Get the elements relative to the last element
      System.out.println(context.getValue("/stringList[last()]"));
      System.out.println(context.getValue("/stringList[last()-1]"))
      System.out.println(context.getValue("/stringList[last()-2]"))
      
      String [] stringArray = (String []) context.getValue("/stringArray");
      System.out.println(Arrays.toString(stringArray));
      
      //Get the elements relative to the last element
      System.out.println(context.getValue("/stringArray[last()]"));
      System.out.println(context.getValue("/stringArray[last()-1]"))
      System.out.println(context.getValue("/stringArray[last()-2]"))
      
  }

}
   

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

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



 
  


  
bl  br