|
JXPath allows you to traverse complex graphs of objects quickly and tersely, using the W3C standard XPath syntax (http://www.w3.org/TR/xpath, and a tutorial is available at http://www.w3schools.com/xpath/). Although XPath was originally designed to provide a standardized mechanism for dealing with complex XML documents, JXPath extends the XPath syntax to support dealing with a wide variety of complex Java data types. To understand the use of JXPath, start by considering a simple hierarchical structure of people. These people are described by Java objects based on the Person class, as shown in Figure 8-1. Notice that each Person has a gender at a minimum and optionally a mother, father, and children. Figure 8-1. Person class.
Given a Person object, consider the typical Java code needed to retrieve a male grandchild of a specific child, as shown in Listing 8-1. The code involves several loops and if statements to find the desired targetdifficult to write and debug. Listing 8-1. Normal Complex Java Object RetrievalPerson bob = FamilyFactory.getPerson(); Iterator children = bob.getChildren().iterator(); while (children.hasNext()) { Person child = (Person)children.next(); if (child.firstName.compareTo("Jon") == 0) { Iterator grandchildren = child.getChildren().iterator(); while (grandchildren.hasNext()) { Person grandchild = (Person)grandchildren.next(); if (grandchild.getGender() .compareTo(Person.FEMALE) == 0) System.out.println(grandchild); } } } The JXPath-based code shown in Listing 8-2 produces output identical to the code shown in Listing 8-1 but is significantly shorter. Listing 8-2. JXPath Complex Java Object RetrievalPerson bob = FamilyFactory.getPerson(); JXPathContext context = JXPathContext.newContext(bob); String searchTerm = "children[firstName='Jon']/children[gender='female']"; System.out.println(context.getValue(searchTerm)); Obviously, the code in Listing 8-2 is much easier to write and work with, assuming you are familiar with the XPath syntax (in Listing 8-2, the searchTerm string). In this chapter, we'll look at how to use JXPath to retrieve objects from a potentially very complex object graph. |
|