XML Node Name – AS3 Gotcha
Posted on | March 4, 2010 | No Comments
Just a quickie, but one that stumped me for about 20 minutes (admittedly because I didn’t RTFM properly).
It turns out that the name() method of the XML class in AS3 returns an object not, as I was assuming, a String. I have a simple switch statement which was taking specific action depending on the name of the XML node it encountered. In psuedo-code it looks like this:
for each (var child:XML in myXMLList) {
switch (child.name()) {
case "node-a":
trace("my name is node-a")
break;
case "node-b":
trace("my name is node-b")
break;
default:
trace("I am an unrecognised node called " + child.name())
break;
}
}
The above will always end up in the default case, and return “I am an unrecgonised [etc]” because the result of the name() method call is an Object and not, as i had assumed, a String.
It took me a while to figure this out because the name() method will evaluate to a String in the trace function through an automatic call to the toString() function, and you will see the localName property of the returned object. Since this is most likely what you are expecting to see, it looks as though nothing is wrong and the Object returned by name() is effectively hidden.
Anyway, the fix is easy and a reminder to read the documentation once in a while. Use either xml.localName() method or xml.name().localName (the latter will return the localName property of the name Object.
Easy when you know how.
Comments
Leave a Reply