A while back I wrote a post on how to access XML using e4x, but I only covered how to get data directly from nodes. Well a few days ago I found myself needing to access a couple attributes from an XML response, so I thought I’d revisit the subject.

Consider the following XML:

var response : XML =
    <response>
        <status interesting="yes">200</status>
    </response>;


To get the data in the ‘status’ node and ‘interesting’ attribute, you’d do the following in your code:

var status : Number = response.status;
var interesting : String = response.status.@interesting;


Simple enough, right?

Now let’s add a namespace declaration to the XML:

var response : XML =
    <response xmlns:sample="https://userflex.wordpress.com/"&gt;
        <status interesting="yes">200</status>
    </response>;


To get at this data, you first need to retrieve the default namespace. Then you can use a similar scheme to get the node and attribute data:

var xmlns : Namespace;
var namespaces : Array = response.namespaceDeclarations ();

for each (var ns : Namespace in namespaces)
{
    if (ns.prefix == "")
    {
        xmlns = ns;
        break;
    }
}

var status : Number = response..xmlns::status;
var interesting : String = response..xmlns::status.@interesting;



Pro Tip: Let’s say you just want to check if an XML attribute has a particular value. You can accomplish that with this little bit of e4x magic:

var yesList : XMLList = response..*::status.(@interesting == "yes");
var isInteresting : Boolean = (yesList.length () > 0);