Archive

Posts Tagged ‘URLRequest’

Simple XML Loading example

February 10th, 2009

Hi,

This is a very simple “tutorial”, more like a how-to, just to practice my writing skills.

First of all we must create an

object:

But to be able to do this, we need to import it, and also import URLRequest, like this:

import flash.net.URLLoader;
import flash.net.URLRequest;

also import the next classes we’ll use:

import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;

create the loader object:

var loader : URLLoader = new URLLoader();
// listen for the COMPLETE event
loader.addEventListener(Event.COMPLETE,
this.onLoadComplete);
// add error event handler
loader.addEventListener(IOErrorEvent.IO_ERROR,
this.onIOErrorEvent);
loader.addEventListener(
SecurityErrorEvent.SECURITY_ERROR,this.onSecurityErrorEvent);

Now that we’re done initializing the loader object, we must create an URLRequest object that will be passed as the request parameter for the load method:

var request : URLRequest = new URLRequest("path_to_file.xml");
// load the file
loader.load(request);

// Now we must create the functions (event handlers) :
function onIOErrorEvent(event : IOErrorEvent) : void {
// handle the error here
// for now just trace the error
trace(event);
}

function onSecurityErrorEvent(event : SecurityErrorEvent) : void {
// handle the error here
// for now just trace the error
trace(event);
}

function onLoadComplete(event : Event) : void {
// the loaded data is in event.target.data
// so create a new XML object
// the XML constructor throws a catchable error if the xml we
// loaded is mallformed
// thus we'll use a try-catch block

var xml : XML;
try {
xml = new XML(event.target.data);
} catch (e : Error) {
// just ouptut the error for now
trace(e);
}

if (xml != null)
{
// our xml is created; use it here
}
}

This is a common way of loading any data, not just xml, if you don’t need access to the bytes loaded until the loading is complete.

Actionscript 3.0 , , , , , , ,