Prior to AS3, working with XML was a drag. The semantics of manipulating an XML object definitely left much to be desired. Well, AS3 changed all that by bringing us E4X. If you don’t already know, E4X stands for ECMAScript for XML and it introduces some new functionality that makes working with XML a lot easier.
Here’s an example working with some inline XML:
//create a new XML object var company:XML = <employees> <employee id="1"><name>John</name><dept>IT</dept></employee> <employee id="2"><name>Susan</name><dept>Marketing</dept></employee> </employees>;
Pretty simple right? Next, let’s create a function for some reusable code to help illustrate:
//create a printer function since we'll be reusing this routine function echo() { //print the data to the output panel for each (var e in company.employee) { trace( "Employee: "+e.name+" works in the "+e.dept+" Dept." ); } } //print the results echo();
We’re just using a for..each loop to iterate through our XML and give us the info we want. The important thing to note is that we can just use the node names. No more ambiguous firstChild, nextSibling, lastChild, etc.
Let’s add a new employee…
//to add a new employee company.employee += <employee id="3"><name>Carl</name></employee>; //print the results echo();
Now, say we wanted to search the XML for that specific employee and assign them to a department. Here’s one way that could work:
//assign Carl to a department company.employee.(@id==3).dept = "Research"; //print the results echo();
Here we used what’s called a filter predicate (a/k/a – the condition to match) and it’s just like the WHERE clause in a SQL statement…“SELECT employee FROM company WHERE id = 3″. So, we’re grabbing the employee element(node) from the company XML tree where the employee attribute, id (@id) is equal to 3.
Now that we’re cooking, what about external XML? Well, that’s no biggie. It’s only slightly different than it was in AS2. To do it, we’ll need to use (2) new AS3 classes: URLLoader and URLRequest. URLRequest replaces getURL() and you can think of URLLoader like MovieClipLoader which allows us to monitor loading and do stuff in response to it. Ok, so with that in mind:
var company:XML; var loader:URLLoader = new URLLoader(); var request:URLRequest = new URLRequest( "company.xml" ); loader.load( request ); loader.addEventListener( Event.COMPLETE, onComplete ); function onComplete( event:Event ):void { var loader:URLLoader = URLLoader( event.target ); company = new XML( loader.data ); trace( company.toXMLString() ); }
And we’re just scratching the surface of what E4X has to offer. That alone is worth the price of admission to the world of AS3…


