Search code examples
xmlactionscript-3e4x

E4X XML filtering and only one result


Consider this XML:

<root>
    <node>
        <subNode>123</subNode>
        <anotherNode>abc</anotherNode>
    </node>
    <node>
        <anotherNode>abc</anotherNode>
    </node>
</root>

This works, because E4X only finds 1 match, and returns an XML instead of an XMLList:

trace(myXml.node.subNode); // 123

But why this throws an Error #1065: Variable subNode is not defined?

trace(myXml.node.(subNode == 123).anotherNode);

Why doesn't it trace <anotherNode>abc</anothernode> ?


Solution

  • This doesn't work because the player tries to find subNode in each node, and it can’t, so a ReferenceError exception is thrown.

    In this case you can use hasOwnProperty method to ensure that the property exists:

    trace(myXml.node.(hasOwnProperty("subNode") && subNode == 123).anotherNode);