JXPath has a number of interesting uses. One very interesting use is to query java collections. So, instead of iterating over a collection and doing lots of if foo then bar, you can instead do it in a succinct XPath query.

Here's a quick code sample I grabbed from an onjava.com article http://www.onjava.com/pub/a/onjava/2004/12/22/jakarta-gems-1.html?page=2:

// assume that the "people" collection contains a list of Person objects.

// This is a list of Person who have a value of "US" for person.getCountry(), and a value greater than 1000000 for person.getJob().getSalary().
List richUsPeople = queryCollection( ".[@country = 'US']/job[@salary > 1000000>@salary > 1000000]/..", people );
// This is a list of Person who have a value of "GB" for person.getCountry(), and a value of "Tony" for person.getName().
List britishTony = queryCollection( ".[@country = 'GB' and @name = 'Tony']", people );
// this is a list of String which contains all the results of person.getJob().getName() for all person objects in the people collection.
List jobNames = queryCollection( query3, "./job/name" );

In terms of efficiency, it's obviously not going to be any more efficient than simply iterating. But, if you're doing this on a small scale then it can make the code cleaner.

The code for queryCollection is:

import org.apache.commons.jxpath.JXPathContext;

public List queryCollection(String xpath, Collection col) {
    List results = new ArrayList();

    JXPathContext context = JXPathContext.newContext( col );

    Iterator matching = context.iterate( xpath );

    while( matching.hasNext() ) {
        results.add( matching.getNext() );
    }
    return results;
}
Version 6.1 last modified by Geoff Fortytwo on 11/07/2010 at 19:22

Attachments 0

No attachments for this document
Website Top
Send Me Mail!:
   g42website4 AT g42.org
My Encyclopaedia Blog

Creator: Geoff Fortytwo on 2008/05/12 01:16
Copyright 2004-2007 (c) XPertNet and Contributing Authors
1.3.2.9174