O'Reilly logo

Jakarta Commons Cookbook by Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

12.4. Applying XPath Queries to Complex Object Graphs

Problem

You need to use XPath expressions to select objects from a complex object graph referencing the contents of a Map and using expressions with variable references.

Solution

Use Jakarta Commons JXPath to select objects from a collection using XPath queries. The following example uses Commons Digester to parse an XML file into an object graph, and selects Planet objects with a radius greater than 5000:

import org.apache.commons.digester.Digester;
import org.apache.commons.digester.xmlrules.DigesterLoader;
import org.apache.commons.jxpath.JXPathContext;

List planets = new ArrayList( );

// Parse Planet XML into a List of Planet objects
InputStream input = getClass( ).getResourceAsStream("./planets.xml");
URL rules = getClass( ).getResource("./planet-digester-rules.xml");
Digester digester = DigesterLoader.createDigester(rules);
digester.push(planets);
digester.parse( input );

// Select all planets with a radius greater than 5000
System.out.println( "Planet Name where radius > 5000");
JXPathContext context = JXPathContext.newContext( planets );
Iterator iterator = context.iterate(".[@radius > 5000]/name");
while( iterator.hasNext( ) ) {
    Object o  = (Object) iterator.next( );
    System.out.println( "Object: " + o);
}

The Planet objects are filtered and the names of planets with sufficient radii are printed to the console:

Planet Name where radius > 5000
Object: Venus
Object: Saturn

This object graph was created from an XML document ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required