views:

400

answers:

2

Why does the trace in the loop below return false for every iteration, even though there ARE nodes named with 6 of the 8 possible values??? This only happens when I have a namespace. Is there some other way to check for the node values???

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
        <![CDATA[
            private namespace ltrs = "letters";

            use namespace ltrs;

            private var myArray:Array = ["a","b","c","d","e","f","g","h"];

            private function checkXML():void
            {
                for each (var p:String in myArray)
                {
                    trace(myXML.hasOwnProperty(p).toString()); // returns false;
                }
            }
        ]]>
    </mx:Script>

    <mx:XML id="myXML">
        <root xmlns="letters">
            <a>true</a>
            <b>true</b>
            <c>true</c>
            <e>true</e>
            <f>true</f>
            <g>true</g>
        </root>
    </mx:XML>

    <mx:Button click="checkXML();" />
</mx:Application>
+2  A: 

The method hasOwnProperty just doesn't work with XML nodes. I believe this is to the E4X specification. However, you can always ask for a node with E4X even if it's not there and just see what the length of the XMLList is that you get back. Like so:

trace(myXML[p].length());

EDIT: As noted below, I was wrong about the hasOwnProperty bit. It does work with XML, and it is a namespace issue that's causing your problem. You can make sure your XML is using the correct namespace by using this handy snippet:

if (myXML.namespace("") != undefined) {
    default xml namespace = myXML.namespace("");
}
Branden Hall
hasOwnProperty works fine with XML nodes. Check the docs on it:http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/XML.html#hasOwnProperty()
Alex Jillard
Ah, you're correct! E4X is a bit of an odd duck since you can do various operations directly inline in ways that you really can't anywhere else in ActionScript.
Branden Hall
A: 

I think the problem resides in the namespace. Try it without, or try xmlns:letters = "letters"

Alex Jillard
removing the namespace is not an option, unfortunately. .length() works great though.
Eric Belair