Iterating Through an XMLList


Developers must often iterate, or loop, through an XMLList object. ActionScript 3.0 provides a few ways to do this. We'll use the same catalog example to demonstrate three different ways to iterate through the products and add up the price values. Here again is the literal syntax for creating the catalog object:

var catalog:XML = <catalog>    <product >       <name>Product One</name>       <price>50</price>    </product>    <product >       <name>Product Two</name>       <price>35</price>    </product> </catalog>;


The first method of iterating through an XMLList is a simple for loop. We use the XMLList.length() method to get the number of items in the XMLList. Then we simply iterate that number of times, incrementing the index (i) with each iteration. You use a similar syntax to loop through an indexed array.

var total:Number = 0; for(var i:int = 0; i < catalog.product.length(); i++) {    total += (catalog.product[i].price as Number); }


The second method is a for...in loop that iterates over the XMLList. This method is commonly used to loop over an associative array or an object.

var total:Number = 0; for(var i:String in catalog.product) { total += (catalog.product[i].price as Number); }


The third method is new to ActionScript 3,0. It's a for each..in loop and provides a cleaner way to loop over XML.

var total:Number = 0; for each(var product:XML in catalog.product) {    total += (product.price as Number); }


It's also possible to use the new for each..in loop structure to iterate over attributes in an XML object.

var product:XML = <product  name="Product One" price="50" />; for each(var attribute:XML in product.@*) {    trace(attribute.name() + ": " + attribute.toXMLString()); }





Advanced ActionScript 3 with Design Patterns
Advanced ActionScript 3 with Design Patterns
ISBN: 0321426568
EAN: 2147483647
Year: 2004
Pages: 132

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net