Previous Page
Next Page

Recipe 20.6. Reading Elements in an XML Tree

Problem

You want to extract the child elements of an XML object.

Solution

Use the elements( ) method to return all of the elements as an XMLList and a for each loop to iterate over the list.

Discussion

You'll often want to "walk" (traverse) an XML tree to extract or examine one or more elements. This is convenient for searching for a given element or processing elements in which you don't know (or don't care about) their precise order.

E4X provides a convenient elements( ) method that returns all of the element child nodes of an XML object. By using this method inside a for each loop, you can walk through the XML tree:

var menu:XML = <menu>
                 <menuitem label="File">
                   <menuitem label="New"/>
                 </menuitem>
                 <menuitem label="Help">
                   <menuitem label="About"/>
                 </menuitem>
                 This is a text node
               </menu>;

for each ( var element:XML in menu.elements(  ) ) {
  /* Displays:
  File
  Help
  */
  trace( element.@label );
}

The preceding example demonstrates that the elements( ) method only returns the child nodes of an XML object that are of type element (ignoring the other node types like text). It also only returns the immediate children of the XML object. The New and About menuitems are not returned by the menu.elements( ) call in the previous code snippet because they are not immediate children of the menu element. To walk the entire tree, you'll need to create a recursive function, as follows:

var menu:XML = <menu>
                 <menuitem label="File">
                   <menuitem label="New"/>
                 </menuitem>
                 <menuitem label="Help">
                   <menuitem label="About"/>
                 </menuitem>
                 This is a text node
               </menu>;

/* Displays:
File
New
Help
About
*/
walk( menu );

// A recursive function that reaches every element in an XML tree
function walk( node:XML ):void {
  // Loop over all of the child elements of the node
  for each ( var element:XML in node.elements(  ) ) {
    // Output the label attribute
    trace( element.@label );
    // Recursively walk the child element to reach its children
    walk( element );
  }
}

See Also

Recipe 20.7, 20.8, and 20.9


Previous Page
Next Page
Converted from CHM to HTML with chm2web Pro 2.85 (unicode)