« Generating Dynamic XML With E4X in ActionScript | Main | New AIR 2.0 API: URLRequest.idleTimeout »
October 26, 2009
Referencing ActionScript Reserved Words in E4X
If you have a chunk of XML with reserved ActionScript words in it, you won't be able to use E4X syntax like you're used to. For instance, say you need to parse the following XML:
var codeXML:XML =
<code>
<class name="Order">
<function name="getId">
<access>public</access>
<return>Number</return>
</function>
</class>
</code>;
Since this XML is full of reserved words, you won't be able to access nodes like this:
trace(codeXML.class.function.return);
Instead, use bracket syntax like this:
trace(codeXML["class"].@name);
trace(codeXML["class"]["function"].access);
trace(codeXML["class"]["function"]["return"]);
Posted by cantrell at October 26, 2009 1:19 PM
Comments
Another option. May be considered a little cleaner:
codeXML.elements("class").attribute("name");
codeXML.elements("class").elements("function").access;
codeXML.elements("class").elements("function").elements("return");
Posted by: Josh at October 26, 2009 3:46 PM
Wouldn't it be cleaner to use the xml methods?
codeXML.child("class").@name
Would it fail?
Seeing codeXML["..."] just looks odd to me (not that it is bad style just a preference thing). :-)
Posted by: John C. Bland II at October 26, 2009 8:44 PM
Thanks for the heads up, but is there any plan to fix this so the awesome workaround isn't required?
Posted by: Tim at October 27, 2009 5:55 AM
Yes, you can always use XML methods in any circumstance. But part of the point of E4X syntax is not to use XML methods. The bracket syntax gives you a more succinct expression (especially since you usually only have one reserved word rather then the extreme example above). The bracket syntax is also not well documented which is why I wanted to blog it.
But of course you should always use whatever is easiest on your eyes.
Christian
Posted by: Christian Cantrell at October 27, 2009 10:39 AM
Yeah, I definitely didn't know you could use bracket syntax so it is good to know for sure.
Posted by: John C. Bland II at October 29, 2009 11:13 AM