Loading and Parsing XML in Actionscript 3 – Part 1
In this first example, I’m going to show you how to load an external XML file into flash using actionscript 3 (as3). I like using XML for external config files or when the client will need to edit the content without flash.
Let’s dig in! here is what the code will look like when we finish.
var xmlLoader:URLLoader;
var xml:XML;
var _request = new URLRequest("http://www.myDomain.com/myXML.xml");
_xmlLoader = new URLLoader(_request);
_xmlLoader.addEventListener(Event.COMPLETE, onXMLLoad);
private function onXMLLoad(e:Event) {
xml = new XML(e.target.data);
// this is where you would parse your XML object.
}
So let’s breakdown the above code to help you understand how it is all working:
1. First we create our variables for the URLLoader and the XML objects we will be using.
var xmlLoader:URLLoader;
var xml:XML;
The URLLoader class is used to load the external file into flash.
2. Next lets initiate the loading sequence.
var _request = new URLRequest("http://www.myDomain.com/myXML.xml");
_xmlLoader = new URLLoader(_request);
_xmlLoader.addEventListener(Event.COMPLETE, onXMLLoad);
_request is stated as a new URLRequest and is passed the URL to our external XML file. Now we state _xmlLoader as a new URLLoader and it requires one parameter, a URLRequest (_request). On the line below that, we add an event listener to listen for when the XML loading has been completed. When finished loading, the onXMLLoad method will be called.
3. By now the XML has finished loading and we are ready to create our XML object and ready it for parsing.
private function onXMLLoad(e:Event) {
xml = new XML(e.target.data);
// this is where you would parse your XML object.
}
The onXMLLoad method is passed one parameter from the event. Within this parameter, we will be able to access the new XML data that was loaded. This new information can be pulled from the event that is passed (e) into this method. Once the XML has been created with the new data, you are ready to parse and organize it.
Please check back soon for part two in which I’ll explain how to parse the new XML data in a format easy to use.
