E4X Selection by Attribute in Flex

My colleague David Meeuwis showed me a most useful and non-intuitive tip that explains a subtle difference between using the @ axis and the attribute() axis in E4X. For example, given the following XML fragment…


<names>
<name salutation="Mr">Billy Bob Thorton</name>
<name salutation="Mrs">Angelina Jollie</name>
<name>Brad Pitt</name>
<name salutation="Ms">Jennifer Aniston</name>
<name salutation="Mr">Vince Vaugn</name>
</names>

The AS3 expression below…

myXml.name.(@salutation == 'Mr')

…will find all the names that have a salutation attribute equal to ‘Mr’. However, if there is any name in the xml that doesn’t have a salutation attribute, that query will throw an exception and die. However…

myXml.name.(attribute('salutation') == 'Mr')

Will give back all names that have a salutation attribute equal to ‘Mr’ and ignore any name elements without a salutation attribute.

So unless you are absolutely positive that the attribute you are selecting always exists, you should be using the attribute() axis over the @ axis.

Here is a quick Flex example with view source enabled that you can test with.

Leave a Reply