AS3 Literal Syntax for XML
ActionScript 3 has all sorts of cool things. One of them is support for “E4X”, which is “ECMAScript for XML”. In other words, it’s got built-in XML primitives. Poorly documented primitives.
One of these primitives is the ability to insert literal XML code right in your app, and have it magically compile into XML objects at runtime. This has lots of handy uses. I’m using XML as a simple communication protocol between two apps, so I don’t need to load XML files… I just want to send small blobs of prefabricated XML back and forth. But of course I don’t want it to be entirely prefabricated… I want to insert variables and such into it. In my case, I wanted to have a prefabricated blob that also had dynamically-generated children.
Insert Dynamic Values Into Nodes: If you look in the help for this, you are directed to the friggin’ E4X specification, in PDF format! There is no documentation other than that. If you google around, you can find that embedding stuff in curly braces {} lets you insert literal symbols. This blob will insert the literal value of “foo” into the XML nodes stored in “cmd”:
var cmd:XML =<cmd><id>{foo}</id></cmd>;
Great! So far, so good. But now, I want to embed several CHILDREN in there, not just the literal value of one node. How do I do it? I tried setting “foo” to a string like “<child>5</child><child>6</child>” etc., but the <> symbols in my string were helpfully turned into < and > so it was still just the textual value of a single node.
Insert Dynamic NODES into your static structure: So how do you do this? I can’t find a way to magically do this directly in the literal XML. Instead, I left the dynamic part of the data out of the literal, and after it was constructed, I tacked the missing parts into the XML structure. To dynamically create nodes, you can explicitly construct an XML object with a string of text, and it will make that into XML node thingies. Then you can use the += operator to insert those nodes into your literal XML. Let me show you an actual small code snippet:
public function sendCmdSetDeckList(deckIdx:uint, ids:Array):void {
var idxml:String = “<abilities>”;
for (var loop:int = 0; loop < ids.length; ++loop) {
idxml += “<ability><id>” + ids[loop].toString() + “</id></ability>”;
}
idxml += “</abilities>”;
var msg:XML =<cmd>
<id>{ID_SEND_SETDECKLIST}</id>
<deckIdx>{deckIdx}</deckIdx>
</cmd>;
msg.cmd += new XML(idxml);
send(msg); // casts “msg” into a String and sends it out on a network socket
}
