orthopedic pain management

Flashuser

  • Pin It

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

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]
<?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>
[/xml]

2. The actionscript 3.0 code for extracting the xml file data:
[as3]
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]);

}
}
[/as3]

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.

Author: Alin

Passionate about web and graphic design, photography and climbing. Follow me at Twitter , Facebook and Google+

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

    Good post, thank you for sharing.