XML e4x and the attributes issue (Error #1065)

Hi All,

The e4x syntax for working with XML and XML data in Flex is widely common now.

However, last week I encountered one error – the error #1065 – claiming that one of the attributes is not defined in the XML.

Here is what actual problem was:
I was using the e4x syntax to find a few nodes in the XML which have a particular attribute value.

Here is the XML that I was using:

<?xml version="1.0" encoding="utf-8"?>
<catalog>
    <album artistCode="001" artistName="Artist1">
        <name>Album 1</name>
    </album>
    <album artistCode="002" artistName="Artist2">
        <name>Album 2</name>
    </album>
    <album artistCode="001" artistName="Artist1">
        <name>Album 3</name>
    </album>
    <album artistCode="002" artistName="Artist2">
        <name>Album 4</name>
    </album>
    <album artistCode="003">
        <name>Album 5</name>
    </album>
</catalog>

now, If I am referring to the above XML by the name of dataXML:XML inside the script, then by writing the following, I can get all the nodes as an XMLList for a particular artistCode (001 in the following case):

dataXML.album.(@artistCode=="001")

This works correctly, I get Album 1 and 4 in the XMLList. But what if I want to search based on the name, then code is modified as follows:

dataXML.album.(@artistName=="Artist1")

But… When I do this, I get an error:

ReferenceError: Error #1065: Variable @artistName is not defined.

 

This is because if you see the last node of album doesn’t have the artistName attribute et al. So how to fix this.

This is actually not too difficult to fix, simply change the code to:

dataXML.album.(attribute("artistName")=="Artist1")

Writing the above code will simply ignore the nodes which do not have that particular attribute and hence will cause no error.

So to conclude, it is important to note that, if you are using XML.node.(@attributeName=’SomeValue’); to search for nodes in your XML data, make sure that all the nodes have that particular attribute, even a blank value is fine, but if the attribute is completely missing, then a run time error will occur. And to avoid it, instead of using the @attribute syntax switch over to (attribute(“attributeName”)) syntax.

I hope this helps someone.

Cheers and wish you all a very happy and prosperous 2010.

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

[...] XML e4x and the attributes issue (Error #1065) flex.gunua.com/?p=127 – view page – cached The e4x syntax for working with XML and XML data in Flex is widely common [...]

Thanks, exactly what I was looking for!

Leave a comment

(required)

(required)