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 ...

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.