There are a few tutorials in line – and I don’t know if I ever get them ready to be published. So I decided to start in small pieces. This piece is one of the fundamentals: Loading and parsing XML in Actionscript 3. (I assume you are familiar with OOP and classes in AS3)…

We are going to read in a simple XML -file. Create one and name it „playlist.xml“.

This is how it looks like:

	

        
		
	
	
		
	
	
		
	

Now, in Flash the IDE (or whatever you like), open the actions-panel and put in that code:

// import the needed classes
import flash.net.URLLoader;
import flash.net.URLRequest;

// create a loader object
var loader:URLLoader = new URLLoader();
// get xml-url via URL-request
var xmlURL = new URLRequest('playlist.xml');
// now add an event-listener to wait for XML to be loaded - then call the function "parseXML"
loader.addEventListener(Event.COMPLETE, parseXML);
// okay, action -> load the thing!
loader.load(xmlURL);

// this function is executed when the xml has loaded
function parseXML(e:Event):void
{
	// now we do whatever we want to do
	var _xml:XML = new XML(e.target.data);
	trace(_xml);
       
       // EXAMPLE: use the "image" in a XMLList
      var myList:XMLList = new XMLList(_xml.image);
      // now pick the url of the 2nd element (for use in loops or whatever)
      someTextField.txt = myList[1]@url;

}

What does it do?

1. We open a connection to the file – by using the standard-URLRequest which will be loading something (well, it could be nearly everything!) into the loader-object. This is an instance of the URLLoader object.

// URLLoader object
var loader:URLLoader = new URLLoader();
// get xml-url via URL-request
var xmlURL = new URLRequest('playlist.xml');

2. We load the file and beforehand we add an eventlistener to the loader object. If the XML has loaded completely (COMPLETE), we call the function „parseXML“ and do whatever we need to do with the XML data.

// event listener
loader.addEventListener(Event.COMPLETE, parseXML);
// go, get it!
loader.load(xmlURL);

3. Parsing the XML data. What you are going to do now depends on what you are aiming at in the end. I prefer to put the xml-data into an XMLList-object. With that I can handle all items easily. (And for the FLEXers it’s compulsory when using the data with components!)

var _xml:XML = new XML(e.target.data);

	trace(_xml.image);
	/* result: 

	  
	
	

	  
	
	

	  

	*/

	trace(_xml.image[1].@url);
	// result: images/2.jpg

	trace(_xml.image[0].description);
	// result: Lorem ipsum dolor

Or, if you need it, create an XML-List out of the xml, like this:

// create an xml-list from the single elements
	var myList:XMLList = new XMLList(_xml.image);
	trace(myList);

Dieser Post ist auch verfügbar auf: Englisch