Menu:

Sponsor

Discover Master of Alchemy, our first iPad/iPhone and iPod touch game!

 

Forum's topics

Latest Files

Archives

Top Rated

Categories

Photo Gallery


E4X in ActionScript 3.0

Introducing

Actionscript 3.0 finally introduced the powerful XML handling E4X ECMAScript for XML.
This new class introduces a new way to look at the XML strings using native actionscript objects.
You can read the full specifications of this powerful sub-language at http://www.ecma-international.org/../Ecma-357.htm

The old way XML class is still available for backward compatibility (see XMLDocument) but it's better to use the new XML class.

1. Load the XML in Actionscript 3.0

As we know there were many changes in ActionScript3 and not only about xml, but also in the way files should be loaded. For example we will use in this tutorial this xml file, which will be used for all the tests with E4X:

import flash.net.URLLoader
import flash.net.URLRequest
import flash.xml.XML
import flash.event.*
import flash.error.*

var mainXML:XML;
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onComplete);
loader.load(new URLRequest("http://www.sephiroth.it/tutorials/flashPHP/E4X/files/test.xml"));

function onComplete(evt:Event)
{
    mainXML = new XML(loader.data)
    trace("xml loaded, start parsing using E4X syntax");
}
            

In the onComplete handler we've created a new instance of XML class, populated with the string received from test.xml.
Ok, now we can procede to parse the XML

2. Validating parser

For many years we used the XML flash object without having a validatign parser and in fact for so much time I've seen horrible XML formatted files with hundreds of errors. For example many people used to create XML files without a root node!
But flash always accepted them without saying nothing :)
Now if we try to initiate a non valid XML we will also get an exception saying the XML is not a valid XML.
For example try to load an xml with a unclosed tag and you'll get this exception:

TypeError: Error #1085: The element type "channel" must be terminated by the matching end-tag "".
            

For this reason we can catch the exception in this way:

function onComplete(evt:Event)
{
    try
    {
        mainXML = new XML(loader.data)
    } catch(e:Error)
    {
        trace("Error: " + e.message)
        return;
    }
}