Loading XML into Flash using ActionScript 3

You may seen many of the Data Driven web and AIR applications developed using Flash ActionScript or Flex.
Here I am going to show you how we can load XML Data into Flash using ActionScript to make data driven flash or AIR application.
Create a class named “XMLLoader” and save the file with the same name of class.
[as3]
package com.ajaybadgujar.dataloader{
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.Event;
import flash.events.IOErrorEvent;

public class XMLLoader{

public static var onSuccess:Function = null;
public static var onFailure:Function = null;

public static var _request:URLRequest = null;
public static var _urlLoader:URLLoader = null;

public static function loadXML(_fileName:String, _onSuccess:Function, _onFailure:Function):void{

onSuccess = _onSuccess;
onFailure = _onFailure;
trace(‘Data load prepairing’);
var url:String = _fileName;
_request = new URLRequest(url);
_urlLoader = new URLLoader();
trace(“Loading XML…..”);
_urlLoader.load(_request);
_urlLoader.addEventListener(Event.COMPLETE, onComplete);
_urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onError);

}

private static function onComplete(e:Event):void {
_urlLoader.removeEventListener(Event.COMPLETE, onComplete);
_urlLoader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
onSuccess(XML(e.target.data));
trace(“Loading XML success”);
}

private static function onError(e:IOErrorEvent):void{
trace(‘Connection Error’);
onFailure();
}

}
}
[/as3]
Here is the sample “books.xml”.

Now see the below code, how you can load above XML by using XMLLoader class.
[as3]
package{
import flash.display.Sprite;
import com.ajaybadgujar.dataloader.XMLLoader;

public class Main extends Sprite{

private var filename:String = “books.xml”;

public function Main() {
// Load XML
XMLLoader.loadXML(filename, TraceXML, XMLLoadingFail);
}

public function TraceXML(_xml:XML):void{
trace(“Result: \n” + _xml);
}

public function XMLLoadingFail():void{
trace(“Loading XML Failed”);
}

}

}
[/as3]
And here is the result
loading_xml_into_flash_using_actionscript

Download Source

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *