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"]);

6 Responses to Referencing ActionScript Reserved Words in E4X

  1. Josh says:

    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”);

  2. Wouldn’t it be cleaner to use the xml methods?codeXML.child(“class”).@nameWould it fail?Seeing codeXML[“…”] just looks odd to me (not that it is bad style just a preference thing). 🙂

  3. Tim says:

    Thanks for the heads up, but is there any plan to fix this so the awesome workaround isn’t required?

  4. Christian Cantrell says:

    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

  5. Yeah, I definitely didn’t know you could use bracket syntax so it is good to know for sure.

  6. strudel says:

    What if a XML uses namespaces?