Skip to main content

If you don't have an IBM ID and password, register here.

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

The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

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.

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

All information submitted is secure.

Tip: Traversing an XML document with a TreeWalker

Navigate your DOM tree while maintaining parental relationships

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.

Summary:  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.

View more content in this series

Date:  01 Oct 2002
Level:  Introductory

Comments:  

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

About the author

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.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in

If you don't have an IBM ID and password, register here.


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. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

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.

(Must be between 3 – 31 characters.)


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

 


Rate this article

Comments

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

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
author1-email=nicholas@nicholaschase.com
author1-email-cc=

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

For articles in technology zones (such as Java technology, Linux, Open source, XML), Popular tags shows the top tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), Popular tags shows the top tags for just that product zone.

For articles in technology zones (such as Java technology, Linux, Open source, XML), My tags shows your tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), My tags shows your tags for just that product zone.

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).