14. September 2009

E4X Advanced Filters

Dynamic E4X Node Filters in AS3

Given the following myXML object

<notes hits="0"/>

What I want is to get just the <notes> node.

Simple, but however hardcoded, STATIC solution is

return myXML.Hits.notes[0];

A more dynamic solution, where the E4X statement takes the Nodename as an AS3 parameter looks as follows:

var NodeName:String = "notes"; return myXML.Hits.child(NodeName)[0];

Mind here that the [0] makes the first matching node to be returned as an XML object rather than XMLList.

Dynamic Attribute Filters in AS3

You could use dynamic set attribute filters in square brackets [] as follows:

var attrName:String = "NodeName"; myXML.@[attrName] = "Baron"; // assign a value to the attribute return myXML.@[attrName]; // get all nodes that have a specific attribute

but you may first check if the filter attribute exists before using it for filtering:

either by using the hasOwnProperty() function

myXML.(hasOwnProperty("@myAttribute") && @["myAttribute"] == "Rene");

or (shorter) the attribute() function

myXMLa.(attribute("myAttribute") == "Rene");

Note that E4X attribute filters don't work in switch statements: For details see --> http://www.zorked.com/flash/e4x-attribute-filter-doesnt-work-in-switch-statements/

Find below some good articles on advanced E4X Filtering:

Keine Kommentare: