Flash and XML – an overview
XML data can be used to influence almost any aspect of a Flash movie's operation dynamically - i.e. the presentation is configured when the movie runs, not when the project is programmed. Applications include on-line games, CD ROMs where some content must be kept up to date and networked applications where information must be passed between users.
When an XML Document is parsed by an instance of the XML class, it is converted into a special, structured object-based data form. Each Tag is converted into one or more data objects called an XMLNode which has its own properties which can include a name, type, text and a list of any children it has.

XML data can be used to influence almost any aspect of a Flash movie's operation dynamically - i.e. the presentation is configured when the movie runs, not when the project is programmed. Applications include on-line games, CD ROMs where some content must be kept up to date and networked applications where information must be passed between users.
Flash gives the capability to parse, manipulate and extract information from XML documents through the use of the XML class and its associated classes. These make Flash a very powerful platform for programming with XML Actionscript 3 has a new XML-handling API which is even easier to use than that used in earlier versions (although AS2.0 classes can still be used). This handout will use the AS 3.0 classes, wrapped in a custom class for convenience and ease of reuse.
XML data in FlashWhen an XML Document is parsed by an instance of the XML class, it is converted into a special, structured object-based data form. Each Tag is converted into one or more data objects called an XMLNode which has its own properties which can include a name, type, text and a list of any children it has.
A Child of a Node corresponds to either a Tag which was contained in the original or the text of that tag.
For example the XML fragment: -
<Ingredient>
<Qty unit="g">100</Qty>
<Item>Cheddar cheese</Item>
<Prep>Sliced thinly</Prep>
</Ingredient>
Would be turned into the following data structure inside Flash: -
There are only 2 types of nodes that are created in Flash; elements which are non-text tags and text that are the text elements (i.e. the data content) of tags.
Example 1 – Loading XML data
We can access the information belonging to any particular node, or get a reference to a node itself by using the various functions and properties of the XML class:-
// make a new XML object
var xmlObj:XML = new XML();
// or create an XML type directly
var xmlObj:XML = <person>
<firstName>Ian</firstName>
<lastName>Willcock</lastName>
</person>;
// gets a reference to the firstName node’s data in an XMLDoc
var firstName:String = xmlObj.firstName;
// gets an XMLList of all child nodes
var children:XMLList = xmlObj.*;
// this gets the number of child nodes
var numNodes:Number = nodeRef.children().length;
We will use an xml parser object to wrap the loading and parsing objects in an easy to use object. We’ll make it advise us of common load errors and make use of a custom Event to tell other parts of the application when the xml is successfully parsed. Here is the full class UML diagram: -

We will incorporate this class into an image viewer application which will be based on the auto-slide example from the Working with Dynamic Assets tutorial. It will load images according to the filenames found in an XML configuration file (see Introduciton to XML tutorial).
Further developments

We will incorporate this class into an image viewer application which will be based on the auto-slide example from the Working with Dynamic Assets tutorial. It will load images according to the filenames found in an XML configuration file (see Introduciton to XML tutorial).
- Copy all your files (i.e. auto_slideshow.fla, the images folder and AssetManager.as) from the auto-slideshow example into a new project folder.
- Save your exhibition.xml file (see tutorial) into your new project folder
- Rename the auto_slideshow.fla file as auto_slideshow_xml.fla
- Open this file in Flash.
- Select File > New. Choose a new Actionscript File.
- Carefully type the following: -
- Save your XMLParser class as XMLParser.as
- Insert 10 frames at the beginning of the main timeline so that the main label is at frame 20.
- Move your preload script to frame 13 and the init label to frame 10.
- Put a new label called xml load at frame 1, your timeline should look like this : -
- Select frame 1 in the scripts layer and open the Actions panel. Type the following :-
package {
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.*;
import flash.errors.*;
public class XMLParser extends EventDispatcher {
public static var PARSING_DONE:String = "parsingDone";
// instance properties
private var xmlObj:XML;
private var loader:URLLoader;
private var filePath:String;
private var success:Boolean;
// the constructior function
public function XMLParser(){
xmlObj = new XML();
loader = new URLLoader();
// add event listeners
loader.addEventListener(Event.COMPLETE, completeListener);
loader.addEventListener(IOErrorEvent.IO_ERROR, ioerrorEventListener);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorListener);
XML.ignoreWhitespace=true;
success = false;
}
//parse a file
public function parse(fileName:String):void{
filePath=fileName;
// start loading
try{
loader.load(new URLRequest(fileName));
} catch (er:Error){
trace("XMLParser: Error - unable to load file "+fileName);
}
}
private function completeListener(e:Event):void{
// make sure XML is valid
try{
xmlObj = XML(loader.data);
trace("XMLParser: Info - load complete "+filePath);
success = true;
dispatchEvent(new Event(XMLParser.PARSING_DONE));
} catch (er:TypeError){
trace("XMLParser: Error - parsing "+er.message);
}
}
private function ioerrorEventListener(e:IOErrorEvent):void{
trace("XMLParser: Error - could not load "+filePath);
}
private function securityErrorListener(e:SecurityErrorEvent):void{
trace("XMLParser: Error - not permitted to load "+filePath);
}
public function getRoot():XML{
if(success){
return xmlObj;
} else {
return null;
}
}
}
}

// script for xml load
import XMLParser;
// make a new parser
var xmlMan:XMLParser = new XMLParser();
// add an event listener
xmlMan.addEventListener(XMLParser.PARSING_DONE,parsingDoneListener);
// load and parse configuration file
xmlMan.parse("exhibition.xml");
// wait for parsing to finish
stop();
function parsingDoneListener(ev:Event):void{
trace("received a parsing done event from XML Parser");
this.gotoAndPlay("init");
}
- Select frame 10 in the scripts layer - the init label. Alter the code so it is as follows :-
- Select frame 13 in the scripts layer, (this should be where your movie checks if the image files have been loaded), we need to edit this so it loops back to frame 12 because it is now at a different frame: -
- That’s it, your movie is finished. Test it by pressing the CONTROL and ENTER keys together.
//script for init
// the node names in the xml file that we're interested in
var contNodeName:String = "contents";
var fileNodeName:String = "f_name";
// make an array of loader instances
var loaders:Array = new Array();
var loadCount:int = 0;
// extract information from our xml file
// first get to the contents part of our xml file
// (i.e. first item on the list of nodes called 'contents')
var contNode:XML = xmlMan.getRoot()[contNodeName][0];
if (contNode != null){
// go through each 'work' node in turn
for each (var workNode:XML in contNode.*){
// get the child node called 'f_name'
var picNode:XML = workNode[fileNodeName][0];
if (picNode != null){
// if there’s a node, make a Loader and start the load
try{
loaders[loadCount] = new Loader();
loaders[loadCount].contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,ioerrorListener);
loaders[loadCount].contentLoaderInfo.addEventListener(Event.COMPLETE,completeListener);
loaders[loadCount].load(new URLRequest("images/"+picNode));
loadCount++; // keep track of the number of files
} catch (e:SecurityError){
trace("Not allowed to load from there!");
}
trace("Found image name: "+picNode);
} else {
// no file node found
trace("Could not find node "+fileNodeName);
}
}
} else {
trace("Error: Could not find a node called "+contNodeName);
stop();
}
// wait while the assets load
stop();
// the event listeners
function ioerrorListener(ev:IOErrorEvent):void{
trace("Something went wrong with the load");
}
// called when a load finishes
function completeListener(ev:Event){
// reduce the number of outstanding loads each time
loadCount-=1;
// have all finished?
if (loadCount==0){
gotoAndPlay("main");
}
}
// see if all the assets have loaded yet
if (this.pics.loaded()) {
// all loaded, go on
this.gotoAndPlay("main");
} else {
// not yet, wait for loading to finish
this.gotoAndPlay(12);
}
At the moment, we are not using all the data we have put in our xml file. See if you can add the following: -
- Create a custom dataType (i.e. an ActionScript class) that would hold all the information about each picture that is present in your xml file.
- Rewrite the code in frame 10 so that each time it finds a picture node, it creates an instance of your custom data class, fills it with data from the xml file and then stores it in an array.
- Rewrite the code in frame 20 so that as well as displaying the pictures, it also shows the title and comments for each image.
This page was last updated on 31st October 2013