XML Filtering
Arguably, the most powerful and useful feature of E4X is its ability to filter data. This new feature
To use filtering, you can enclose expressions in parentheses as part of an E4X expression. The following examples show a few uses of filtering. We'll use the same XML object for all our examples:
var catalog:XML = <catalog>
<product id="0">
<name>Product One</name>
<price>50</price>
</product>
<product id="1">
<name>Product Two</name>
<price>35</price>
</product>
</catalog>;
The following line retrieves the product element that has an id attribute equal to 1. This example returns just one XML object, but it would return an XMLList if more than one element matches the criteria.
var product1:XML = catalog.product.(@id == 1);
This
var cheapestProductName:String = catalog.product.(price < 50).name; This example retrieves the product elements that have a price greater than 35 and less than 50:
var productRange:XMLList = catalog.product.(price >= 35 && price <= 50); |
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
var catalog:XML = <catalog>
<product id="0">
<name>Product One</name>
<price>50</price>
</product>
<product id="1">
<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 id="0" name="Product One" price="50" />;
for each(var attribute:XML in product.@*) {
trace(attribute.name() + ": " + attribute.toXMLString());
}
|