Loading XML data in Flash using ActionScript

By Blue_Chi | Flash CS3 | ActionScript | Intermediate

XML can be used to load external data in Flash to provide an easy method for structuring content so that it is easy to understand, process, and update. This tutorial will teach you the basics on how to create a Flash-friendly XML file and how to load and process this XML file in Flash using the ActionScript XML object. You are assumed to have intermediate knowledge of ActionScript in order to follow this tutorial.

What is XML?

XML stands for Extensible Markup Language, it is used to structure data logically using tags that look very similar to HTML. You do not need any preliminary knowledge about XML to understand the intended function of the example code below:

<gallery>
<image name="school">image1.jpg</image>
<image name="garden">image2.jpg</image>
<image name="shop">image3.jpg</image>
</gallery>

XML makes it possible for authors to create and name their tags in whatever form they choose as long as they adhere to the basic rules of the language.

The tags of an XML document define elements which are structured in a parent/child manner, where each tag may have a number of children tags but only one parent.

XML Parent/Child Relationship

XML tags are called nodes in ActionScript. Each node may contain a number of optional attributes that contain a value specified within quotation marks.

Our earlier code could be re-written in the following generalized format:

<root-node>
<child-node attribute="value">sub-child-node</child-node>
<child-node attribute="value">sub-child-node</child-node>
<child-node attribute="value">sub-child-node</child-node>
<root-node>

Writing an XML File for Flash

XML is made up of just text and could be created using any text editor. It is important to note that good practice requires you to create one root node for all same level nodes. For an XML file to work, each tag must be closed, either by using a closing tag or by closing self-contained nodes by placing a backslash / at the end of the tag if it does not contain text content (or a text node) within it. We are not using any self contained nodes in this tutorial, but they are very commonly used, their generalized format is <node-name attribute="value" />.

We will use the same code we used earlier to follow the rest of this tutorial. Copy the code below and paste in in the note pad and then save the file as oman3d.xml.

<gallery>
<image name="school">image1.jpg</image>
<image name="garden">image2.jpg</image>
<image name="shop">image3.jpg</image>
</gallery>

Loading XML in Flash

We are going to load the XML data we created above in Flash now. The XML() class must be used to load and control XML into Flash, the process for loading an XML file in Flash using this object could be summarized in the following manner:

  1. Create an instance of the XML class.
  2. Create a function to process XML when loaded.
  3. Load XML file.

ActionScript can load and process XML by using the XML() class. Similar to many other classes in ActionScript, we must create an instance of this class before we can use any of its methods or properties.

var myXML:XML = new XML();

In order for Flash to process our XML file properly, we have to make sure that it does not consider the spaces and line-breaks between our nodes as additional nodes (which it does if we didn't do the following), we have to set the .ignoreWhite property to true so that Flash ignores all the white spaces between the nodes.

myXML.ignoreWhite=true;

To load the XML file we simply use the .load method directly on the instance that we created.

myXML.load("oman3d.xml");
Due to security restrictions, Flash can only load XML files residing on the same domain as the SWF file.

We then attach a function to the .onLoad event handler property of our XML object to process our XML when the the file has successfuly loaded. Our code will output the entire contents of our XML document.

myXML.onLoad = function(success){
if (success){
trace (myXML);
}

Processing the XML file

There is no point in using XML if you are going to output the entire content of the file without processing it as if it were a simple text file because you could have done that with the simpler LoadVars class and a text file instead. The power of XML is in making use of the logic of the node structure to extract and process the information that you need from the file.

The most essential tools that you will be using over and over again to access specific content of your XML file are the .firstChild property, the .childNodes[] property, and the .attribute property of an XML node.

.firstChild

If you use proper formating for your XML file, all of your nodes would be wrapped by a root node, in our example, this would be the <gallery> node. To access the inner contents of this node, we simply refer to it this way, it is pretty self explanatory.

myXML.firstChild;

You can use the .firstChild property to access deeper nodes within your XML file. So if you would like to access the first child of your first child node, you simply tag them together back to back, in the example below, we will be accessing the contents of our first <image> node.

myXML.firstChild.firstChild;

the .firstChild property could also be used to access the actual textual content of a node if it has any, in the example that we have, our XML file has the URL of each image as the actual content of each <image> node. To access this content, we attach another .firstChild property to our existing chain.

myXML.firstChild.firstChild.firstChild;

//to test this to see that it shows you the URL use the trace method:
trace(myXML.firstChild.firstChild.firstChild);

When using complex scripts,as your text content of a node, if for example you have quotation marks or slashes in your test, you might need to use the .nodeValue property to make sure that all the contents of your node as read as text:

myXML.firstChild.firstChild.firstChild.nodeValue;

.childNodes

The .firstChild property allows you only to access the first child of a node, but in the majority of cases, you would probably have more than one child to each of your nodes, so you will have to use other ways to access these nodes, ActionScript provides a property called .nextSibling, which can be used for access a sibling of a child node, but I find this property very tiring to use and prefer the .childNodes property instead. The .childNodes is an array containing a list of all the child nodes of a parent node. Because this is an array we can use it to tell us the number of child nodes a parent node has using the array .length property. If the code below was to be traced, it should give out 3 as our <gallery> node has three child nodes.

myXML.firstChild.childNodes.length;

//use trace to see how many child nodes <gallery> has
trace(myXML.firstChild.childNodes.length);

Using the .childNodes property it is possible to access any of the childes of the nodes using the square [] operator, and just like all arrays, the first element in the array is located at number zero, the second at 1, the third and 2. We will access the three elements we have in our array this way:

myXML.firstChild.childNodes[0];
myXML.firstChild.childNodes[1];
myXML.firstChild.childNodes[2];

To acquire the text value of one of these child nodes, we use the .firstChild operator the same way we did earlier.

myXML.firstChild.childNodes[2].firstChild;

It is possible to use ActionScript loops to create powerful effects and processes for cycling through an XML file.

.attributes

You should be able now to access any node within an XML file using a combination of .firstChild and .childNodes properties, to be able to access the value of any attribute within any of these nodes you use the .attributes property attached to the name of the attribute that you would like to access. These attributes are created by the author of the XML file, in this case us, and we know that each <image> node has a title attribute. We can access its value this way:

myXML.firstChild.childNodes[2].attributes.title;

Other properties and methods

You should be aware of the existence of other properties and methods available for accessing data in the XML file and to navigate through its various nodes, which were not discussed in this tutorial.

Semi-Practical Example

Our code extracts the contents of our XML file and displayes it in the output window in a structured format. A loop is used to cycle through the XML file to get the content of all the nodes.

var myXML:XML = new XML();
myXML.ignoreWhite=true;
myXML.load("oman3d.xml");
myXML.onLoad = function(success) {
if (success) {
var myImage = myXML.firstChild.childNodes;
for (i=0; i<myImage.length; i++) {
var imageNumber = i+1;
var imageName = myImage[i].attributes.title;
var imageURL = myImage[i].firstChild.nodeValue;
trace ("My image number "+imageNumber+" is titled "+imageName+" and its URL is "+imageURL+".")
}
}
};

This concludes our tutorial, our upcoming tutorials will show you real-life examples on how to make use of XML to create powerful Flash effects. Please feel free to post all your questions at the Oman3D Forum.

- End of Tutorial.