Bobby Smith

Bobby Smith

Experience Designer.

AS3 XML Loader Class

01 February, 2010

I’ve written an XML loader class, as well as a custom event class, for Actionscript 3 that you can use in your flash/flex projects to easily load an external XML file.

{  
     import flash.net.URLLoader;  
     import flash.net.URLRequest;  
     import flash.events.Event;  
     import flash.events.EventDispatcher;  

public class LoadXML extends EventDispatcher  
 {  

    private var dataXML:XML;  

    public function LoadXML(xmlFileName:String):void  
     {  
         var xmlLoader:URLLoader = new URLLoader(new URLRequest(xmlFileName));  
         xmlLoader.addEventListener(Event.COMPLETE, loadedCompleteHandler);  
     }  

    private function loadedCompleteHandler(e:Event):void  
     {  
         e.target.removeEventListener(Event.COMPLETE, loadedCompleteHandler);  
         try {  
             dataXML = new XML(e.target.data);  
             dispatchEvent(new CustomEvent(CustomEvent.ONLOADED,dataXML));  
         } catch(e:Error) {  
             throw new Error(<span class="st0">"Unable to load XML file");  
         }  
     }  
 }

} 

Here’s what you’ll need to get it working in your scripts.

//-------- IMPORT CLASSES  
 import com.reversetype.utils.LoadXML;  
 import com.reversetype.utils.CustomEvent;  

//-------- CREATE INSTANCE OF LOADER CLASS  
     var myLoadXML = new LoadXML(xmlFileName)  
     myLoadXML.addEventListener(CustomEvent.ONLOADED, xmlComplete);  

//-------- METHOD TO HANDLE THE RETURNED DATA  
   private function xmlComplete(e:CustomEvent):void  
   {  
     myData = e.data;  
     trace(myData);  
   }