12.3. Search a Collection of Simple Objects

Problem

You need to select objects from a Collection using XPath predicates.

Solution

Use Jakarta Commons JXPath to select objects from a Collection using predicates in XPath expressions. The iterate( ) method on JXPathContext takes an XPath expression and returns an Iterator that contains each node satisfying that expression. The following example uses simple XPath predicates to select Person objects from a List by age, first name, and position:

import org.apache.commons.jxpath.JXPathContext; // Create a List of Person objects List people = new ArrayList( ); people.add(new Person("Ahmad", "Russell", 28 ); people.add(new Person("Tom", "Russell", 35 ); people.add(new Person("Ahmad", "Abuzayedeh", 33 ); // Select all people older than 30 System.out.println( "** People older than 30"); JXPathContext context = JXPathContext.newContext( people ); Iterator iterator = context.iterate(".[@age > 30]"); printPeople(iterator); // Select all people with a first name of 'Ahmad' context = JXPathContext.newContext( people ); System.out.println( "** People with first name 'Ahmad'" ); iterator = context.iterate(".[@firstName = 'Ahmad']"); printPeople(iterator); // Select the second person from the List context = JXPathContext.newContext( people ); System.out.println( "** Third Person in List" ); Person p = (Person) context.getValue(".[2]"); System.out.println( "Person: " + p.getFirstName( ) + " " + p.getLastName( ) + ", age: " + p.getAge( ) ); // A method ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.