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 retrieving multiple results from JXPath expression using JXPathContext.iterate() API.
//Create JXPathContext with ComplexBean object as ROOT node
JXPathContext context = JXPathContext.newContext(bean);
//Iterate through first three values
Iterator<?> firstThreeVals = context.iterate("/stringList[position() < 4]"); while (firstThreeVals.hasNext()) {
System.out.println(firstThreeVals.next());
}
//Iterate except first two values
Iterator<?> exceptFirstTwoVals = context.iterate("/stringList[position() > 2]"); while (exceptFirstTwoVals.hasNext()) {
System.out.println(exceptFirstTwoVals.next());
}
BookStore bookStore = new BookStore(
Arrays.asList( new Book("A1", 11.11, new Author("X1")), new Book("B2", 22.22, new Author("X2")), new Book("C3", 33.33, new Author("X3")), new Book("D4", 44.44, new Author("X4"))
)
);
//Create JXPathContext with BookStore object as ROOT node
JXPathContext bookContext = JXPathContext.newContext(bookStore);
//Get the first two books
Iterator<?> firstTwoBooks = bookContext.iterate("/books[position() < 3]");
Book book = null;
while (firstTwoBooks.hasNext()) {
book = (Book) firstTwoBooks.next();
System.out.println(book);
}
}
}
It gives the following output,
Maths
Physics
Chemistry
Chemistry
Hindi
English
Book[A1]
Book[B2]