E4X or ECMAScript for XML is ActionScript 3.0′s native support for XML. This allows easy access to XML for programmers . To show how to use E4X, we’re first going to need some sample XML:
For this XML, the root node is “zoo”, each animal has one attribute, “name” and two child nodes (also called child elements) “type” and “sex”.
When using E4X expressions, the root node is not used so to access the animal nodes, we would use the expression
animals.animal this returns all the animal nodes that are the direct descendant of the animals node. In this case that would be leo, karen and susan NOT fred. To get only the first animal node, we would use
We can use predicate filtering to return only data that satisfies the provided conditions. For example, to get the animal named leo, we would use
animals.animal.(@name=="leo") the @ symbol is used to indicate we’re using an attribute. To get the female animals, we would use
animals.animal.(sex=="female") this would give us the data for karen and susan. You can apply predicate filtering multiple times to further restrict the result set.
Remember how animals.animal only returns the direct children of animals? Using the descendant accessor “..” we can access all the descendants and return them wherever they are below our starting point. Thus using
..animal we can return not only leo, karen and susan but fred too.
ArrayCollection sorting and cursors
To sort an ArrayCollection, we need to define a Sort object which contains an array of SortField objects. The SortField objects define the fields the ArrayCollection is to be sorted by (in order). The Sort object has a fields property to take this array. For only one field, we could define our sort as follows:
var mySort:Sort = new Sort();
mysort.fields=[new SortField("field name to sort by")];
There are three optional parameters for SortField objects:
- case sensitivity (default false)
- ascending or descending (default descending)
- numeric or alphabetic (default is alphabetic)
Once we have our sort defined, we assign it to the the ArrayCollection’s sort property and then apply the sort by calling the
refresh() method of the collection.
A cursor is a position indicator that allows direct access to any item in a collection. You can move a cursor forwards, backwards, find specific items and retrieve, add or remove items at the cursor position.
Any class that implements the ICursorView interface can use cursors.
The steps to using a cursor are:
- create the cursor using the collection’s
- sort the collection
- use cursor methods such as
findAny()to locate items in the collection
cursor.currentto address the item at the cursor position (must cast to the item type)
findAny() may have a slight performance advantage.