Tip: Traversing an XML document with a TreeWalker

Navigate your DOM tree while maintaining parental relationships

XML's Document Object Model provides objects and methods that enable a developer to navigate a document's tree, but typically the process involves NodeLists and recursive methods that make it easy to get lost within the structure. The DOM Level 2 Traversal module provides a new object, the TreeWalker, which simplifies this process and makes navigation more reliable. This tip demonstrates the process of determining whether a TreeWalker is available and how to use it to extract information from a document.

Share:

Nicholas Chase (nicholas@nicholaschase.com), President, Chase and Chase, Inc

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.



01 October 2002

Also available in Japanese

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

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.


Traversing the tree

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.


Moving around the tree

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.

Resources

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into XML on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=XML
ArticleID=12175
ArticleTitle=Tip: Traversing an XML document with a TreeWalker
publish-date=10012002