Date display area
Flash and XML (ActionScript 2)
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.

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 (more so than Director). Flash 9 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 2.0 classes, wrapped in a custom class for convenience.

XML data in Flash
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.

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: -

xml data structure diagram

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.

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(); // make it load an xml file xmlObj.load(“myfile.xml”); // gets a reference to the first node in an XMLDoc var rootNode:XMLNode = xmlObj.firstChild; // gets a node's name trace(nodeRef.nodeName); // this gets the number of child nodes var numNodes:Number = nodeRef.childNodes.length;

Example 1 – Loading XML data
We will use an xml parser object that has a mix of instance and static elements. Here is the full class UML diagram: -

XMLParser 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).
  1. Copy all your files (including the images, Timer.as and AssetManager.as) from the Dynamic Assets tutorial into a new project folder.

  2. Save your exhibition.xml file (see tutorial) into your new project folder

  3. Rename the auto_slideshow.fla file as auto_slideshow_xml.fla

  4. Open this file in Flash.

  5. Select File > New. Choose a new Actionscript File.

  6. Carefully type the following: -

  7. class XMLParser { private var xmlObj:XML;//XML oader and parser private var target:Object;// object to notify private var timer:Timer;// timer for this object private var success:Boolean; // constructor function public function XMLParser(myTarget:Object) { // create a new instance of the XML parser xtra this.xmlObj = new XML(); // set it to ignore white space characters this.xmlObj.ignoreWhite = true; this.timer = new Timer(50, this); this.target = myTarget; this.success = false; } // parse a file public function parse(fileName:String):Void { // start loading and parsing this.xmlObj.load(fileName); this.timer.startTimer(); } // called by the timer object private function update():Void { if (this.xmlObj.loaded) { this.timer.stopTimer(); // parsing has finished - check for errors var err = this.xmlObj.status; if (err == 0) { trace("Parsing successful"); // no errors this.success = true; } else { // something went wrong - tell the user trace("Couldn't load xml, error: "+err); } // send loadDone event with result this.target.loadDone(this.success); } } // returns the root node of the XML doc public function getRoot():XMLNode { // only possible after parsing successfully if (this.success) { // return the root (first) node return this.xmlObj.childNodes[0]; } else { return null; } } // static methods = accessed through Class name // gets the number of children a node has public static function getChildCount(myNode:XMLNode):Number { return myNode.childNodes.length; } // get a child node based on a number (NB starts at 0) public static function getChild(myNode:XMLNode, id:Number):XMLNode { return myNode.childNodes[id]; } // gets a node's name public static function getName(myNode:XMLNode):String { return myNode.nodeName; } // gets the data in a node's data node public static function getData(myNode:XMLNode):String { return myNode.firstChild.nodeValue; } }

  8. Save your XMLParser class as XMLParser.as

  9. Insert 10 frames at the beginning of the main timeline so that the main label is at frame 20.

  10. Move your preload script to frame 13 and the init label to frame 10.

  11. Put a new label called xml load at frame 1, your timeline should look like this : -

  12. XML Load timeline image

  13. Select frame 1 in the scripts layer and open the Actions panel. Type the following :-

  14. // script for xml load // make a new parser var xmlMan:XMLParser = new XMLParser(this); // load and parse configuration file this.xmlMan.parse("exhibition.xml"); // wait for parsing to finish stop(); // this is called by the parser when it has finished function loadDone(success:Boolean){ if (success) { // go and load images this.gotoAndPlay("init"); } }

We now have to alter the code so that the names of the images to load and display are extracted from the XML data structure that has been generated from the configuration file.

  1. Select frame 10 in the scripts layer - the init label. Alter the code so it is as follows :-

  2. // script for init // make a new assset manager var pics:AssetManager = new AssetManager(this); // first get to the contents part of our xml file var rootNode:XMLNode = xmlMan.getRoot(); var contNode:XMLNode = undefined; // go through child node of 'data' for (var i:Number = 0; i<XMLParser.getChildCount(rootNode); i++) { var myNode:XMLNode = XMLParser.getChild(rootNode, i); // is its name 'contents'? if (XMLParser.getName(myNode) == "Contents") { // yes - store this node contNode = myNode; } } //if a contents node was found, load pictures if (contNode != undefined) { // now go through and get the filename for each picture for (var i:Number = 0; i<XMLParser.getChildCount(contNode); i++) { // get a work node var picNode:XMLNode = XMLParser.getChild(contNode, i); // now get the nodes inside (filename, title etc.) for (var n:Number = 0; n<XMLParser.getChildCount(picNode); n++) { var myNode:XMLNode = XMLParser.getChild(picNode, n); if (XMLParser.getName(myNode) == "F_Name") { // filename - get it loaded this.pics.addAsset("images/"+XMLParser.getData(myNode)); } if (XMLParser.getName(myNode) == "Title") { // title - just print for now trace("found picture: "+XMLParser.getData(myNode)); } } } } else { trace("Could not find a node called 'Contents'"); stop(); }

  3. 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: -

  4. // 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); }


  5. That’s it, your movie is finished. Test it by pressing the CONTROL and ENTER keys together.
Further developments
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 12th January 2009