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

Processing XML with for-each-in and for-in

XML-structured documents often contain data sets that need to be processed systematically. For example, an XML document might contain population information for the countries of the world, or points on a map, or the costs of items in an order. Whatever the data, the basic approach is the same—each item must be examined and used in some uniform way by the application. In order to make XML-formatted information easy to process, E4X adds a new kind of loop to ActionScript called the for-each-in loop.

The for-each-in loop, which we first saw in Chapter 15, provides easy access to the values of an object's dynamic instance variables or an array's elements. Recall the generalized syntax for a for-each-in loop:

for each (variableOrElementValue in someObject) {
  statements
}

We can use the preceding syntax to process XML instances in an XMLList just as easily as we process an array's elements or an object's dynamic instance variables. Example 18-8 demonstrates.

Example 18-8. Using for-in-each to process XML instances

var novel:XML = <BOOK ISBN="0141182806">
    <TITLE>Ulysses</TITLE>
    <AUTHOR>Joyce, James</AUTHOR>
    <PUBLISHER>Penguin Books Ltd</PUBLISHER>
  </BOOK>;
for each (var child:XML in novel.*) {
  trace(child);
}

The for-each-in loop in Example 18-8 runs three times, once for each child node in the XMLList returned by novel.*. The first time the loop runs, the variable child is assigned a reference to <BOOK>'s first child node (i.e., the XML instance representing ...

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