The latest versions of Adobe Flash Player support E4X, which is a set of programming language extensions that add native XML support to ActionScript. These extensions allow you to work with XML in Flex 2 using the same common operators that you already know. Further, they add a small set of new operators to handle common operations, such as searching and filtering.
In this section, you get an overview of the core operators and extensions for using E4X. Understanding these capabilities will greatly enhance your ability to work with XML from within Flex 2.
You can now declare XML literals as you would any integer or string:
var orderInfo:XML = <order>
<item id='1'>
<menuName>burger</menuName>
<price>3.95</price>
</item>
<item id='2'>
<menuName>fries</menuName>
<price>1.45</price>
</item>
</order>;
You can use dot and array syntax already common to most programming languages, and certainly to ActionScript users, to access data in an XML structure:
trace( orderInfo.item[1].menuName ); //fries
You can use the .@ operator to access attributes of an XML node:
trace( orderInfo.item[1].@id ); //2
You can retrieve a list of nodes as an XML list:
trace( orderInfo.item.menuName ); //<menuName>burger</menuName> //<menuName>fries</menuName>
You can use the descendant operator .. to search down the through the XML:
trace( orderInfo..price ); //<price>3.95</price> //<price>1.45</price>
You can also use predicate filtering to filter your results based on conditions:
trace( orderInfo.item(@id==2).price ); //<price>1.45</price> var myID:int = 2; trace( orderInfo.item(@id==myID).price ); //<price>1.45</price>
For the increasing number of developers who use XML as data within their applications, E4X support is critical to daily application development.
There is one small catch, however. E4X is a series of operators—and in ActionScript 3 you don't have any way to evaluate an expression represented as a string at runtime. Take the following string as an example:
var myAddString:String = "2 + 2";
There isn't a way to specify that ActionScript evaluate the expression and return the answer "4." You also don't have the ability to evaluate the following expression against XML within memory:
var myExpression:String = "..item.(@id==2)..price";
Some of you might be asking why anyone would want to do this? Good question. However, instead of answering, let's provide one specific example where this feature is extremely useful and leave the thousands of other possible answers up to you.