Friday, February 13, 2009

Flash Slideshow: ActionScript to Load an XML File

I've seen a few various ways to load an xml file with flash. Each of them suffer from the same problem. They are hard coded for a specific file, and riddled with magic numbers to access xml node data.

Here's some actionscript to load an XML in Flash. Great for loading say a Flash Slideshow from XML.


var slideshow_images:Array;

var data_xml:XML = new XML();
data_xml.ignoreWhite = true;
data_xml.onLoad = function(loaded) {
if (loaded) {
slideshow_images = load_images(data_xml);

//TODO: do something with the images

delete data_xml;
}
}

data_xml.load("photos.xml");

function load_images(images_xml) {
var images:Array = new Array();
var cur_image_xml = images_xml.firstChild.firstChild;
while (cur_image_xml != null) {
images.push(get_image_data(cur_image_xml));
cur_image_xml = cur_image_xml.nextSibling;
}
return images;
}

function get_image_data(image_xml) {
var image = new Object();
var image_prop_iter = image_xml.firstChild;
while (image_prop_iter != null) {
//trace(image_prop_iter.firstChild.nodeValue);
image[image_prop_iter.nodeName] = image_prop_iter.firstChild.nodeValue;
image_prop_iter = image_prop_iter.nextSibling;
}
return image;
}







No comments: