O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Traversing XML Trees

In general programming terms, to traverse means to access every node in a data structure and process it in some way. Tree traversal means using a recursive algorithm to traverse the nodes of a tree structure.

In DOM-based XML implementations (such as the legacy flash.xml.XMLDocument class), programmers often write custom code to traverse XML trees when searching for information. For example, a human resources program might include traversal code that searches through an XML document looking for all employees classified as managers or all employees in a certain salary bracket. As we saw in the previous section, such custom tree-traversal code is largely unnecessary in E4X because most searches can be performed using E4X's descendants and filtering predicate operators. However, there are still some situations in which a tree must be traversed, even in E4X. Fortunately, the E4X code for doing so is trivial.

In E4X, we can use the descendants operator in combination with the properties wildcard to retrieve an XMLList containing every descendant node for a given element, as follows:

someElement..*  // Returns a list containing
                // all of someElement's descendants

And we can use the for-each-in statement to iterate over every item in an XMLList. By combining these techniques, we can easily traverse every node in an XML tree as follows:

for each (var child:XML in someElement..*) {  // Process child...
}

Note, however, that the preceding code does not strictly conform to the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required