What's JXPathJXPath provides APIs for traversal of graphs of JavaBeans, DOM and other types of objects using the XPath syntax.
If you are not familiar with the XPath syntax, start with
XPath Tutorial by W3Schools
.
XPath is the official expression language of XSLT. In XSLT, you mostly use XPath to access various elements of XML documents. You can do that with JXPath as well. In addition, you can read and write properties of JavaBeans, get and set elements of arrays, collections, maps, transparent containers, various context objects in Servlets etc. In other words, JXPath applies the concepts of XPath to alternate object models. You can also have JXPath create new objects if needed.
The central class in the JXPath architecture is
Object Graph TraversalJXPath uses JavaBeans introspection to enumerate and access JavaBeans properties.
The interpretation of the XPath syntax in the context of Java
object graphs is quite intuitive: the JavaBean Property AccessJXPath can be used to access properties of a JavaBean. public class Employee { public String getFirstName(){ ... } } Employee emp = new Employee(); ... JXPathContext context = JXPathContext.newContext(emp); String fName = (String)context.getValue("firstName");
In this example, we are using JXPath to access a property
of the
Note that using the XPath Lenient Mode
The Nested Bean Property AccessJXPath can traverse object graphs: public class Employee { public Address getHomeAddress(){ ... } } public class Address { public String getStreetNumber(){ ... } } Employee emp = new Employee(); ... JXPathContext context = JXPathContext.newContext(emp); String sNumber = (String)context.getValue("homeAddress/streetNumber"); In this case XPath is used to access a property of a nested bean. A property identified by the XPath does not have to be a "leaf" property. For instance, we can extract the whole Address object in above example: Address addr = (Address)context.getValue("homeAddress"); Collection SubscriptsJXPath can extract elements from arrays and collections. public class Integers { public int[] getNumbers(){ ... } } Integers ints = new Integers(); ... JXPathContext context = JXPathContext.newContext(ints); Integer thirdInt = (Integer)context.getValue("numbers[3]"); A collection can be an arbitrary array or an instance of java.util.Collection. JXPath also supports indexed properties according to the JavaBeans specification. Note: in XPath the first element of a collection has
index 1, not 0.
Retrieving Multiple Results
JXPath can retrieve multiple objects from a graph. Note
that the method called in this case is not public class Author { public Book[] getBooks(){ ... } } Author auth = new Author(); ... JXPathContext context = JXPathContext.newContext(auth); Iterator threeBooks = context.iterate("books[position() < 4]"); This returns an iterator over at most three books from the array of all books written by the author. Map Element Access
JXPath supports maps. To get a value use its key as the name in
a public class Employee { private Map addressMap = new HashMap(); { addressMap.put("home", new Address(...)); addressMap.put("office", new Address(...)); } public Map getAddresses(){ return addressMap; } ... } Employee emp = new Employee(); JXPathContext context = JXPathContext.newContext(emp); String homeZipCode = (String)context.getValue("addresses/home/zipCode"); Often you will need to use the alternative syntax for accessing Map elements: String homeZipCode = (String)context. getValue("addresses[@name='home']/zipCode"); Unlike a child name in XPath, the value of the "name" attribute does not have to be a properly formed identifier. Also, in this case the key can be an expression, e.g. a variable. The attribute "name" can be used not only with Maps, but with JavaBeans as well. The value of this attribute represents the name of a property. Note: At this point JXPath only supports Maps that use strings for keys. Note: JXPath supports the extended notion of Map: any
object similar to Map, i.e. having some kind of API for accessing
values by key, can be handled by JXPath
provided that its class is registered with the
DynaBean AccessJXPath supports DynaBeans as well. DynaBeans are treated exactly the same way as JavaBeans. DOM/JDOM Document Access
JXPath supports access to DOM and JDOM Nodes. The DOM/JDOM node can be
the context node of JXPathContext or it can be a value of a
property, element of a collection, value of a variable etc.
Let's say we have a path The intepretation of XPath over DOM/JDOM structures is implemented in accordance with the XPath specification. Getting a Value vs. Selecting a Node
JXPathContext has two similar sets of APIs:
Consider the following XML document: <?xml version="1.0" ?> <address> <street>Orchard Road</street> </address>
With the same XPath, Registering Namespaces
When using namespaces, it is important to remember that XPath matches
qualified names (QNames) based on the namespace URI, not on the prefix.
Therefore the XPath
In order to use a namespace prefix with JXPath, that prefix should be
known to JXPathContext. JXPathContext knows about namespace prefixes
declared on the document element of the context node (the one passed
to ContainersA Container is an object implementing an indirection mechanism transparent to JXPath.
For example, if property
An example of a useful container is
XMLDocumentContainer
.
When you create an XMLDocumentContainer, you give it a
pointer to an XML file (a Let's say we have the the following XML file, which is stored as a Java resource. <?xml version="1.0" ?> <vendor> <location id="store101"> <address> <street>Orchard Road</street> </address> </location> <location id="store102"> <address> <street>Tangerine Drive</street> </address> </location> </vendor> Here's the code that makes use of XMLDocumentContainer. class Company { private Container locations = null; public Container getLocations(){ if (locations == null){ URL url = getClass().getResource("Vendor.xml"); locations = new XMLDocumentContainer(url); } return locations; } } ... context = JXPathContext.newContext(new Company()); ... String street = (String)context.getValue( "locations/vendor/location[@id = 'store102']//street"); Like was described before, this code will implicitly open and parse the XML file and find a value in it according to the XPath. Functions id() and key()
Functions
The only situation where no custom coding is needed is when
you want to use the
In order to evaluate the
Similarly, the XPath Axes And Object GraphsThe interpretation of XPath over XML models like DOM and JDOM is governed by the XPath standard. There is no official standard for the interpretation of XPaths on other types of models: beans, maps etc. This part describes how JXPath performs such interpretation. Parent/child RelationshipIn DOM/JDOM the definition of a node's parent is clear: a Node always points to its parent. XML is a strict tree, so there always exactly one parent for every node except the root. With other models the situation is more complex. An general object model can not be described as a tree. In many cases it is a complicated graph with many paths to the same node and even referential cycles where node A is node B's child, but also node B is node A's child. Even if the graph is a strict tree, a node of that tree may not have a pointer to its parent.
Because of all these issues, JXPath abandons the static notion
of a parent/child relationship in favor of a dynamic one.
When an XPath is evaluated, the engine performs a series of searches
and computations in so called evaluation contexts. For example,
when the This chain of contexts is used in JXPath to define the parent-child relationship. Parent is the base node of the previous evaluation context in the chain. A more appropriate name for the "parent::" axis would then be "step back".
Consider this example. The evaluated path is
Exercise: think about how the path
Solution:
The dynamic interpretation of the parent/child relationship affects most axes including "parent::", "ancestor::", "preceding::", "following::" etc. Document OrderThe XPath standard defines the term "document order" as the order in which pieces of XML follow each other in the textual representation. This definition is not applicable directly to non-XML models. Results of many types of xpaths depend on the document order, so we cannot leave it as "unpredictable" or "undefined" for such nodes as JavaBeans or Maps. In order to have a predictable order, JXPath sorts properties of beans and keys of maps alphabetically. AttributesFor JavaBeans and Maps the "attribute::" axis is interpreted the same as the "child::" axis. The only two distinctions are the "xml:lang" and "name".
Attribute
The Exceptions During XPath EvaluationExceptions thrown by accessor methods are treated differently depending on the evaluated xpath and the particular method used to do the evaluation.
The basic idea is that if JXPath is looking for something by
iterating over all properties of a bean and during that iteration
an accessor method for one of these properties throws an exception,
JXPath ignores the exception and moves on to the next property.
This could happen if the method is In all other cases, an exception thrown by an accessor method is wrapped into a JXPathException and re-thrown. Modifying Object GraphsJXPath can also be used to modify parts of object graphs: property values, values for keys in Maps. It can in some cases create intermediate nodes in object graphs. Setting PropertiesJXPath can be used to modify property values. public class Employee { public Address getAddress() { ... } public void setAddress(Address address) { ... } } Employee emp = new Employee(); Address addr = new Address(); ... JXPathContext context = JXPathContext.newContext(emp); context.setValue("address", addr); context.setValue("address/zipCode", "90190"); Creating Objects
JXPath can be used to create new objects. First, create a
subclass of
public class AddressFactory extends AbstractFactory { public boolean createObject(JXPathContext context, Pointer pointer, Object parent, String name, int index){ if ((parent instanceof Employee) && name.equals("address"){ ((Employee)parent).setAddress(new Address()); return true; } return false; } } JXPathContext context = JXPathContext.newContext(emp); context.setFactory(new AddressFactory()); context.createPath("address");
You can also combine creating a path with setting the value
of the leaf: the context.createPathAndSetValue("address/zipCode", "90190"); Note that it only makes sense to use the automatic creation of nodes with very simple paths. In fact, JXPath will not attempt to create intermediate nodes for paths that don't follow these three rules:
VariablesJXPath supports the notion of variables. The XPath syntax for accessing variables is "$varName". public class Author { public Book[] getBooks(){ ... } } Author auth = new Author(); ... JXPathContext context = JXPathContext.newContext(auth); context.getVariables().declareVariable("index", new Integer(2)); Book secondBook = (Book)context.getValue("books[$index]"); You can also set variables using JXPath: context.setValue("$index", new Integer(3)); Note: generally speaking, you can only change the
value of an existing variable this way, you cannot define
a new variable. If you do want to be able to define a new variable
dynamically, implement a When a variable contains a JavaBean or a collection, you can traverse the bean or collection as well: ... context.getVariables().declareVariable("book", myBook); String title = (String)context.getValue("$book/title); Book array[] = new Book[]{...}; context.getVariables().declareVariable("books", array); String title = (String)context.getValue("$books[2]/title); Custom Variable PoolsBy default, JXPathContext creates a HashMap of variables. However, you can substitute a custom implementation of the Variables interface to make JXPath work with an alternative source of variables. For example, you can define implementations of Variables that cover a servlet context, HTTP request or any similar structure. See the org.apache.commons.jxpath.servlet package for an example of just that. Servlet Contexts
The
See static methods of the class
JSP Page Context
The JXPathContext returned by
If you need to limit the attibute lookup to just one scope,
you can use the pre-definded variables Servlet Request Context
The
HttpSession Context
The
ServletContext Context
Finally,
All these methods cache the JXPathContexts they create within the corresponding scopes. Subsequent calls use the JXPathContexts created earlier. Pointers
Often, rather than getting a node in the object graph, you need to
find out where in the graph that node is. In such situations you
will need to employ Pointers. A Pointer is an object that
represents the specific location in the object graph. Effectively,
it is a simple XPath leading from the context root to the selected
node. That simple XPath can be used to repeatedly acquire the same
node of the graph without performing a costly search.
Let's say, you invoke the JXPath search process by calling the
Pointer ptr = context.getPointer("//address[zipCode='90190']") System.out.println(ptr);
This code will find the address with zipCode = 90190 and
return a Pointer describing that node's location. The printed line
will look something like this:
Here's another example: Pointer ptr = context.getPointer("employees[$i]/addresses[$j]")
Let's say, at the time of execution the value of the variable i is 1
and j = 3. If we call If you need to perform an exhaustive search for all nodes in the graph matching a certain XPath, you can get JXPath to produce an iterator returning pointers for all of discovered locations: Iterator homeAddresses = context.iteratePointers("//employee/address[@name='home']"); Each Pointer returned by the iterator will represent a home address object in the graph. It is a good idea to use pointers whenever you need to access the same node of a graph repeatedly. JXPath is optimized to interpret XPaths produced by Pointers much faster than many other types of XPaths. Relative ContextsIf you need to evaluate multiple paths relative to a certain node in the object graph, you might want to create a relative JXPathContext.
First, obtain the pointer for the location that is supposed to be the root
the relative context. Then obtain the relative context by calling
JXPathContext context = JXPathContext.newContext(bean); Pointer addressPtr = context.getPointer("/employees[1]/addresses[2]"); JXPathContext relativeContext = context.getRelativeContext(addressPtr); // Evaluate relative path String zipCode = (String)relativeContext.getValue("zipCode"); // Evaluate absolute path String name = (String)relativeContext.getValue("/employees[1]/name"); // Use the parent axis to locate the employee for the current address Double salary = (Double)relativeContext.getValue("../salary"); Extension FunctionsJXPath supports standard XPath functions right out of the box. It also supports "standard" extension functions, which are basically a bridge to Java, as well as entirely custom extension functions. Standard Extension FunctionsUsing the standard extension functions, you can call methods on objects, static methods on classes and create objects using any constructors. All class names should be fully qualified. Here's how you can create new objects: Book book = (Book)context. getValue("com.myco.books.Book.new('John Updike')"); Here's how you can call static methods: Book book = (Book)context. getValue("com.myco.books.Book.getBestBook('John Updike')"); Here's how you can call regular methods: String firstName = (String)context. getValue("getAuthorsFirstName($book)"); As you can see, the target of the method is specified as the first parameter of the function. Custom Extension Functions
Collections of custom extension functions can be
implemented as
Let's say the following class implements various formatting operations: public class Formats { public static String date(Date d, String pattern){ return new SimpleDateFormat(pattern).format(d); } ... } We can register this class with a JXPathContext: context.setFunctions(new ClassFunctions(Formats.class, "format")); ... context.getVariables().declareVariable("today", new Date()); String today = (String)context.getValue("format:date($today, 'MM/dd/yyyy')"); You can also register whole packages of Java classes using PackageFunctions.
Also, see
Expression Context
A custom function can get access to the context in which it
is being evaluated. ClassFunctions and PackageFunctions
have special support for methods and constructors that have
public class MyExtenstionFunctions { public static boolean isDate(ExpressionContext context){ Pointer pointer = context.getContextNodePointer(); if (pointer == null){ return false; } return pointer.getValue() instanceof Date; } ... } You can then register this extension function using ClassFunctions and call it like this: "//.[myext:isDate()]" This expression will find all nodes of the graph that are dates. Collections as Arguments
There are two ways a collection can be passed to an extension function:
as a
public class MyExtenstionFunctions { ... public static boolean contains(NodeSet nodeSet, Object value){ Iterator iter = nodeSet.getPointers().iterator(); while (iter.hasNext()) { Pointer item = (Pointer)iter.next(); if (item.getValue().equals(value)){ return true; } } return false; } // Alternative implementation public static boolean contains(List list, Object value){ Iterator iter = list.iterator(); while (iter.hasNext()) { Object item = iter.next(); if (item.getValue().equals(value)){ return true; } } return false; } } You can call this function to find all people who have a certain phone number: "/addressBook/contact[myext:contains(phoneNumbers, '555-5555']" Collection as the Return ValueA custom function can return a collection of arbitrary objects or a NodeSet. The simple implementation of NodeSet, BasicNodeSet , may come in handy. Type ConversionsJXPath automatically performs the following type convertions:
InternationalizationFor DOM Documents JXPathContext supports internationalization XPath-style. A locale can be declared on an XML Element like this: <book xml:lang="fr">Les Miserables</book>
You can then use the "//book[lang('fr')]
The
You can also utilize the Nested ContextsIf you need to use the same configuration (variables, functions, abstract factories, locale, leniency etc.) while interpreting XPaths with different beans, it makes sense to put the configuration in a separate context and specify that context as a parent context every time you allocate a new JXPathContext for a JavaBean. This way you don't need to waste time fully configuring every context. JXPathContext sharedContext = JXPathContext.newContext(null); sharedContext.getVariables().declareVariable("title", "Java"); sharedContext.setFunctions(new MyExtensionFunctions()); sharedContext.setLocale(Locale.CANADA); sharedContext.setFactory(new MyFactory()); ... JXPathContext context = JXPathContext.newContext(sharedContext, auth); Iterator javaBooks = context.iterate("books[preprocessTitle(title) = $title]"); Compiled ExpressionsWhen JXPath is asked to evaluate an expression for the first time, it compiles it and caches its compiled representation. This mechanism reduces the overhead caused by compilation. However, in some cases JXPath's own caching may not be sufficient- JXPath caches have limited size and they are automatically cleared once in a while. Here's how you can precompile an XPath expression: CompiledExpression expr = context.compile(xpath); ... Object value = expr.getValue(context); Use compiled expressions if you need to satisfy any of the following requirements:
Customizing JXPathJXPath can be customized on several levels.
Custom JXPathBeanInfo
JXPath uses JavaBeans introspection to discover properties
of JavaBeans. You can provide alternative property lists by
supplying custom JXPathBeanInfo classes (see
Custom DynamicPropertyHandlerJXPath uses various implementations of the DynamicPropertyHandler interface to access properties of objects similar to Map.
The Custom Pointers and Iterators
Architecturally, multiple model support is made possible by
the notions of a
NodePointer
and
NodeIterator
,
which are simple abstract classes that are extended in
different ways to traverse graphs of objects of different
kinds. The NodePointer/NodeIterator APIs are designed with
models like JavaBeans in mind. They directly support
indexed collections. As a result, XPaths like
To add support for a new object model, build custom implementations of NodePointer and NodeIterator as well as NodePointerFactory . Then register the new factory with JXPathContextReferenceImpl . See existing NodePointerFactories for examples of how that's done:
Alternative JXPath Implementation
The core JXPath class, JXPathContext, allows for alternative implementations.
This is why instead of allocating JXPathContext directly, you
should call a static |