Tips & Tricks 4: Loading data from XML file in Actionscript 3.0 June 22, 2009

Tips & Tricks 4: Loading data from XML file in Actionscript 3.0

by flashuser in ActionScript 3.0, Flash Tips & Tricks

In a previews post I wrote about how can you load data from an xml file in Actionscript 2.0. For today’s trick I will show you how can you do that using Actionscript 3.0.

1. Prepare your xml file, here is the sample I will use:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<images>

    <img image="photos/pic1.jpg" description="This is the first image" />

    <img image="photos/pic2.jpg" description="This is the second image" />

    <img image="photos/pic3.jpg"  description="This is the third image" />

</images>

2. The actionscript 3.0 code for extracting the xml file data:

var xmlData = "images.xml";//set xml data file

var xmlObj: XMLDocument;

init();//init call -> load config XML and create objects

function init() {
	xmlObj = new XMLDocument();
	xmlObj.ignoreWhite = true;

	var loader:URLLoader = new URLLoader();
	var request:URLRequest = new URLRequest(xmlData);
	loader.load(request);

	loader.addEventListener("complete", onComplete);
	loader.addEventListener("ioError", onIOError);
}

function onIOError(event:Event):void {
	trace("IOERROR (maybe XML file does not exit or have an incorrect name)");
}

function onComplete(event:Event):void {
	var loader:URLLoader = event.target as URLLoader;
	if (loader != null) {
		xmlObj.parseXML(loader.data);
		xmlHandler();
	} else {
		trace("Loader is not a URLLoader!");
	}
}

function xmlHandler() {
	addObjects();
}

var numItems;
var objects;

var image:Array = new Array();
var description:Array = new Array();

function addObjects() {//add objects in the scene

	objects = xmlObj.firstChild.childNodes;
	numItems = objects.length;

	for (var i=0; i<numItems; i++) {
		var attr = objects[i].attributes;
		//Set the images
		image[i] = attr.image;
		description[i] = attr.description;
		trace("Path image: "+image[i]+" ------description: "+description[i]);

	}
}

For any questions related to this method leave a comment and I will answer as soon as possible.

Here you can download the sample file.

Subscribe to our RSS Feed and follow us on Twitter

Enjoy this post?

Help us grow this site and share the content with others among you.

img-delicious img-digg img-twitter
img-stumbleupon img-facebook img-mixx

Comments
  1. Actionscript 3 seems alot simpler then as2, I am finally getting a hold of as3. `

    Good post, thank you for sharing.


Leave a Comment

Note: You can get a Gravatar account for free so your avatar can be shown when you post a comment on any website that supports gravatars.