Using XML in Flash with Actionscript 3 and E4X

E4X may be the best thing about Flash CS3! It stands for ECMAScript for XML and it is the new way to interact with XML in Flash AS3. What is ECMAScript? I don’t know - nor do I care. What I do know is it ROCKS your socks off. If you have used XML in Flash before you’ll will be amazed at how much easier it is.

Remember this?
xmlInstance.firstChild.firstChild.firstChild.firstChild.firstChild.childNodes[5]?

Now you can do this:
xml.nodeName[5]

It is soooo much easier to do. Thank you AS3.

Take a look at the “Chuck Quotes” swf below. Bask in its utter radness. It randomly selects one of 10 Chuck Norris facts and displays it next to the handsome face of none other than Chuck Norris. Here is the actionscript I used to build this beauty:

var xml:XML = new XML();
var loader:URLLoader = new URLLoader();
loader.load(new URLRequest(”http://www.jesseharding.com/blog/files/chuckisms.xml”));
loader.addEventListener(
Event.COMPLETE,
function(evt:Event):void {
xml = XML(evt.target.data);

var high:Number = xml.chuckism.length()-1;
var low:Number = 0;
var randomNum:Number = Math.round(Math.random() * (high - low)) + low;

var randomChuck:String = xml.chuckism[randomNum].@text;
chuckquote.text = randomChuck;
}
);

I’ve got a sample fla file that is very well commented and shows you how to build the “Chuck Quotes” swf below.

Download the fla here

Here is the Chuck Quotes swf:

You need Flash to see to this

Error in my_thread_global_end(): 4 threads didn't exit