Note: This tip uses JAXP, but the sample application will also work with Xerces-Java 2 and the concepts are applicable for any XML parser environment.
The Document Object Model (DOM) provides interfaces such as Node, which includes methods such as getFirstChild() and getNextSibling(). Along with methods such as getChildNodes(), these methods provide a way to navigate an XML document, typically using recursion to analyze each set of children.
A TreeWalker does much the same thing, but in a more organized way. Rather than recursing through a method, a TreeWalker actually navigates the structure, using methods such as nextNode(). Each time it moves, the currentNode property changes to the new node, so the TreeWalker always knows where it is within the document. For example, in Listing 1, consider a document of employees to contact in case of an emergency:
Listing 1. The source document
<?xmlversion="1.0"?>
<personnel>
<employee empid="332">
<status>contact</status>
<deptid>24</deptid>
<shift>night</shift>
<name>Jenny Berman</name>
</employee>
<!-- Other employees listed here -->
</personnel>
|
A TreeWalker can check the text value of a status element upon encountering one. It can also move back up the document to the employee element and retrieve the empid value before moving on to the next employee rather than analyzing the rest of the employee information.
Creating the TreeWalker object requires a DocumentTraversal object, which acts as a factory for all objects in the Traversal module. Actually instantiating a TreeWalker requires four parameters as in Listing 2:
Listing 2. Instantiating a TreeWalker
...
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Node;
import org.w3c.dom.traversal.DocumentTraversal;
import org.w3c.dom.traversal.TreeWalker;
import org.w3c.dom.traversal.NodeFilter;
public class ShowDocument {
public static void main (String args[]) {
...
DOMImplementation domimpl = doc.getImplementation();
if (domimpl.hasFeature("Traversal", "2.0")) {
Node root = doc.getDocumentElement();
int whattoshow = NodeFilter.SHOW_ALL;
NodeFilter nodefilter = null;
boolean expandreferences = false;
DocumentTraversal traversal = (DocumentTraversal)doc;
TreeWalker walker = traversal.createTreeWalker(root,
whattoshow,
nodefilter,
expandreferences);
} else {
System.out.println("The Traversal module isn't supported.");
}
}
}
|
Note: Because the Traversal module is optional in a DOM implementation, it's a good idea to make sure it's supported before you try to use it.
At creation, the TreeWalker needs to know four things:
- Where to start
- What to look at
- Whether any filtering needs to be done
- Whether to expand entities or simply treat them as references
Setting the starting point to the root element is straightforward. Likewise, a simple boolean value determines whether to expand the entity references.
Determining which nodes are visible to the TreeWalker is a little more complicated. To start with, you have the option of specifying whether it should see all nodes or only a specific type of node. The value, shown here as the whattoshow parameter, can be easily set using constants defined in the NodeFilter interface. The most common value used is NodeFilter.SHOW_ALL, but the interface defines values, such as NodeFilter.SHOW_ELEMENT and NodeFilter.SHOW_TEXT, for each type of node.
A NodeFilter, however, can also play a more complex role. It's possible to create a custom NodeFilter that passes only appropriate values to the TreeWalker. For example, a NodeFilter could pass only the employees who should be contacted. Because the application will initially view all nodes, no NodeFilter is passed to the TreeWalker.
The TreeWalker is now ready to traverse the tree. The simplest case is a walker that starts with the root node and moves down the tree, as seen in Listing 3:
Listing 3. TreeWalker begins traversing the tree
...
TreeWalker walker = traversal.createTreeWalker(root,
whattoshow,
nodefilter,
expandreferences);
Node thisNode = null;
thisNode = walker.nextNode();
while (thisNode != null) {
System.out.println(thisNode.getNodeName()+":"
+thisNode.getNodeValue());
thisNode = walker.nextNode();
}
} else {
System.out.println("The Traversal module isn't supported.");
}
}
}
|
The walker was created with the root as the currentNode, so when nextNode() is first called, it moves to the first text node child of the personnel element and returns that node. The while loop then checks to see whether the currentNode was successfully changed. In this case it was, so the node name and value are output and the walker moves to the next node -- the employee element, which is returned as thisNode. The next time through the loop, the walker moves to the first text child of employee, and so on:
Listing 4. The walker returns null
#text:
employee: null
#text:
deptid: null
#text: 24
#text:
shift: null
#text: night
#text:
status: null
#text: contact
#text:
...
|
The process continues until the walker can no longer move to the next node, and returns null.
Traversing the document is simple enough, but it could have been accomplished by other means. Part of the strength of a TreeWalker is its ability to retain the hierarchical structure of the document during processing. For example, the walker is aware of where it is in the tree, so when it encounters a status element, it can check the value of its text child and then retrieve an attribute from its parent:
Listing 5. The walker responds to a status node
...
thisNode = walker.nextNode();
while (thisNode != null) {
if (thisNode.getNodeName().equals("status")){
Node status = walker.firstChild();
if (status.getNodeValue().equals("contact")){
Node statusNode = walker.parentNode();
Node employeeNode = walker.parentNode();
Element employeeElement = (Element)employeeNode;
String empId = employeeElement.getAttribute("empid");
System.out.println("Now contacting employee number " + empId);
walker.nextSibling();
}
}
thisNode = walker.nextNode();
}
} else {
...
|
In this case, the walker is still traversing the root node, but if it encounters a node named status, it explicitly moves to that node's first child, the text node. The text node becomes the currentNode for the walker. If the text node equals contact, the walker moves back up to the currentNode's parent, the status element, and then that node's parent, the employee element. From there, you can retrieve the attribute value as usual. When finished, you can move directly to the next employee, the sibling of the current employee.
- Check out the DOM
Level 2 Traversal and Range Recommendation.
- Download JAXP or Xerces-Java 2.
- Find more XML resources on the developerWorks XML zone. For a complete list of XML tips to date, check out the tips summary page.
-
IBM trial software: Build your next development project with trial software available for download directly from developerWorks.
- Find out how you can become an IBM Certified Developer in XML and related technologies.
- Want us to send you useful XML tips like this every week? Sign up for the developerWorks XML Tips newsletter.
Nicholas Chase has been involved in Web site development for companies such as Lucent Technologies, Sun Microsystems, Oracle, and the Tampa Bay Buccaneers. Nick has been a high school physics teacher, a low-level radioactive waste facility manager, an online science fiction magazine editor, a multimedia engineer, and an Oracle instructor. More recently, he was the Chief Technology Officer of Site Dynamics Interactive Communications in Clearwater, Florida, USA, and is the author of three books on Web development, including Java and XML From Scratch (Que) and the upcoming Primer Plus XML Programming (Sams). He loves to hear from readers and can be reached at nicholas@nicholaschase.com.