We all know about XML and XPath
Basically XPath is a way to query xml files, similar to
select statements on a database.
Example: Finding the node BBB in the following xml, you
would use the query: /AAA/DDD/BBB
<AAA>
<BBB/>
<CCC/>
<BBB/>
<BBB/>
<DDD>
<BBB/>
</DDD>
<CCC/>
</AAA>
<BBB/>
<CCC/>
<BBB/>
<BBB/>
<DDD>
<BBB/>
</DDD>
<CCC/>
</AAA>
Of course the query options for the XPath are very complex,
and allow easy retrieval of nodes in the xml.
Now let’s say that instead of using xml’s we are using java
classes (either it has nothing to do with xml’s or we marshaled the xml to a
class for processing). In essence the
concept is very much the same. You have an instance graph of classes, and you
want to traverse the graph to get a value on a specific node.
The solution for this is JXPath (http://commons.apache.org/proper/commons-jxpath/).
You can now search your graph using standard xpath expressions.
For example:
Class Address{
String zipCode;
}
Class Location{
Address address;
}
Class Vendor{
List<Location> locations;
}
Old code:
Address address = null;
Collection locations = vendor.getLocations();
Iterator it = locations.iterator();
while (it.hasNext()){
Location location = (Location)it.next();
String zipCode = location.getAddress().getZipCode();
if (zipCode.equals("90210")){
address = location.getAddress();
break;
}
}
JXPath code:
Address address = (Address)JXPathContext.newContext(vendor).
getValue("locations[address/zipCode='90210']/address");
Further reading: