Company
Department
Employee (name, job title, age)
Acme Inc.
Sales
Johnny, Sales rep, 45
Sarah, Sales rep, 33
Magda, Office assistant, 27
Accounting
Steve, Head controller, 51
Peter, Assistant controller, 31
Susan, Office assistant, 27
With that in place, let's start using JXPath!
The simplest query possible extracts a single object from the object tree. For example, to retrieve Company
, use the following code:
JXPathContext context = JXPathContext.newContext(company);
Company c = (Company)context.getValue(".");
The first line shows the creation of a context
, the starting point for all JXPath's XPath expressions in the object tree (comparable to the rootnode
element in an XML document). The second line of code executes the actual query. Since our context
starts at the company level, to retrieve the Company
object, we simply use the current-element selector '.'
.
An Employee
is a child object of a Department
. To retrieve the Employee
named "Johnny" use the following code (Company
is still context
's starting point):
Employee emp = (Employee)context.getValue("/departmentList/employees[name='Johnny']");
Basically, the code reads: "Search all Department
s from the beginning for the Employee
object of which the name
attribute has the value 'Johnny'
."
The above code snippet illustrates how to use a predicate to search objects by using particular values. Using predicates is comparable to using the WHERE clause in SQL. We can even combine multiple predicates in one query:
Employee emp =
(Employee)context.getValue("/departmentList/employees[name='Susan' and age=27]");
Unless you're using an ad-hoc, one-time-only query, implementing hard-coded queries usually isn't feasible. It is better to define a reusable query that you can then execute with different parameters. To accommodate parameterized querying, JXPath supports variables in queries. Using variables, the code above now looks like this:
context.getVariables().declareVariable("name", "Susan");
context.getVariables().declareVariable("age", new Integer(27));
Employee emp =
(Employee)context.getValue("/departmentList/employees[name=$name and age=$age]");
JXPath can provide an iterator over all objects retrieved by a query, much like iterating a result-set. The following snippet shows how you can iterate over all Department
s:
for(Iterator iter = context.iterate("/departmentList"); iter.hasNext();){
Department d = (Department)iter.next();
//...
}
To retrieve all Employee
s from all Department
s and iterate over them:
for(Iterator iter = context.iterate("/departmentList/employees"); iter.hasNext();){
Employee emp = (Employee)iter.next();
//...
}
To retrieve all Employee
s older than 30 years from the sales department:
for(Iterator iter = context.iterate
("/departmentList[name='Sales']/employees[age>30]"); iter.hasNext();){
Employee emp = (Employee)iter.next();
//...
}
And the above example with variables:
context.getVariables().declareVariable("deptName", "Sales");
context.getVariables().declareVariable("minAge", new Integer(30));
for(Iterator iter = context.iterate("/departmentList
[name=$deptName]/employees[age>$minAge]"); iter.hasNext();){
Employee emp = (Employee)iter.next();
//...
}
Those two last code snippets also demonstrate the use of several predicates within one XPath query.
A Pointer
is a JXPath utility object that represents a reference to the location of an object in the object tree. For example, a Pointer
might refer to "the first employee of the second department." Compared to objects retrieved directly from the tree, Pointer
s offer additional functions like the execution of relative queries through relative contexts (more on this later).
Having a Pointer
refer to an object in the object tree is almost identical to directly retrieving objects:
JXPathContext context = JXPathContext.newContext(company);
Pointer empPtr = context.getPointer("/departmentList[name='Sales']/employees[age>40]");
System.out.println(empPtr);
//output: /departmentList[1]/employees[1]
System.out.println(((Employee)empPtr.getValue()).getName());
//output: Johnny
Note that the Pointer
's output demonstrates that a Pointer
describes an object's location, rather than the object itself. Also note that the actual object the Pointer
refers to can be retrieved through the Pointer
's getValue()
method.
Pointers can also be iterated over, as the following snippet demonstrates:
for(Iterator iter = context.iteratePointers("/departmentList[name='Sales']
/employees[age>30]"); iter.hasNext();){
Pointer empPtr = (Pointer)iter.next();
//...
}
Since a Pointer
describes a location, it can be used as a reference point for navigating through the entire object tree. To do that, use the Pointer
as the root object (Remember using the Company
object for that earlier?) in a so called relative context. From this relative context, you can query the entire object tree by executing relative queries. This advanced use of Pointer
s offers great flexibility as the examples below illustrate.
To begin, here's how you create a relative context:
for(Iterator iter = context.iteratePointers("/departmentList[name='Sales']
/employees[age>30]"); iter.hasNext();){
Pointer empPtr = (Pointer)iter.next();
JXPathContext relativeContext = context.getRelativeContext(empPtr);
}
In this code snippet, a new relative context is created for consecutive employee
pointers.
Using the relative context, XPath queries can be executed on the entire object tree of siblings, children, and parent/grandparent objects, as the following snippet demonstrates:
//Current employee
Employee emp = (Employee)relativeContext.getValue(".");
//Employee name
String name = (String)relativeContext.getValue("./name");
//Name of the Department this Employee belongs to (a parent object)
String deptName = (String)relativeContext.getValue("../name");
//Name of the Company this Employee belongs to (a 'grandparent' object)
String compName = (String)relativeContext.getValue("../../name");
//All coworkers of this Employee (sibling objects)
for(Iterator empIter = relativeContext.iterate("../employees"); empIter.hasNext();){
Employee colleague = (Employee)empIter.next();
//...
}
JXPath is an extremely useful tool for traversing, navigating, and querying complex object trees. Because it uses the XPath expression language for its queries, a large body of reference material is available to help you build efficient yet complex object-retrieval queries. Even more flexibility is added by using Pointer
s and relative contexts.
This brief article only scratches the surface of JXPath's possibilities, for a more in depth discussion with more advanced usage examples, read my full tutorial.
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。