I got an interesting question the other day from someone wondering how you can insert variable values when defining an XML structure in ActionScript 3.0. Its actually an interesting feature I haven’t seen a lot of discussion around.
As most of you will probably know, ActionScript 3.0 now treats XML as a native data type meaning its no longer parsed as a String. That does bring with it that the old methods of inserting variable values (e.g. “<value>”+myValue+”</value>”) no longer apply.
So how was this addressed?
Just take a look at the following snippet of code:
package {
import flash.display.Sprite;
public class XMLExample extends Sprite {
private var someXML:XML;
private var myName:String = "Peter";
private var myEmail:String = "info at peterelst dot com";
public function XMLExample() {
someXML =
<friends>
<person name={myName}>
<email>{myEmail}</email>
</person>
</friends>;
trace(someXML.toString());
}
}
}
That’s right, the curly braces notation we know and love from MXML. One difference though, this is *not* an active reference to the variable. If you change the value of the variable this will not update your XML (no, not even in Flex — this is pure AS3 code but you can of course define the XML structure in MXML and take advantage of its data binding features).
Also worth noting is that you don’t put quotes around the curly braces when you use it for an XML attribute, if you do that it’ll treat it as a String rather than eval’ing it. The XML object takes care of generating valid XML from it.
XML is an absolute joy to work with in ActionScript 3.0, if you haven’t tried it yet do it now (and while you’re at it be sure to read up on E4X)!
2 Comments
That’s cool!
I think nobody is talking about it because we get confused… we associate the curly braces only with Flex and its data binding capabilities.
I wonder why Adobe did not use different operators. i.e {myBindableExpression} only for data binding and [anyExpression] for the rest.
That would solve two problems. One: avoid confussion and two: avoid innecessary compiler warnings when assigning no bindable expressions directly in mxml.
Cheers!
Hi,
Do you have a simple example of a swf file with actionscript 3.0 using variables from XML?