Loading XML data using ActionScript 3.0

By Blue_Chi | Flash CS3 | ActionScript 3.0 | Beginner

Using XML is one of the best ways for structuring external content in a logical format that is easy to understand, process, and update. This tutorial will teach you the basics on how to load and process XML in Flash using ActionScript 3.0. You are assumed to have basic knowledge of ActionScript in order to follow this tutorial.

This tutorial is for working with XML in ActionScript 3.0. If you would like to learn how to work with XML in ActionScript 1/2 then please review our previous Flash XML tutorial.

Our tutorial will be divided into the following short sections:

  1. What is XML?
  2. Writing an XML File for Flash.
  3. Loading XML in Flash.
  4. Processing XML in Flash.

What is XML?

XML stands for Extensible Markup Language, it is a markup language used to structure data logically using tags that look very similar to HTML. However, when using HTML you use existing tags to create your web pages, but in XML you create you own tags which you later use in your program the way you choose. This makes it easy to create tags which are descriptive of your project and understandable by any human being. For example, you do not need any preliminary knowledge about XML or the program that uses it to figure out the purpose of the sample code below:

<?xml version="1.0" encoding="utf-8"?>
<GALLERY>
<IMAGE TITLE="school">image1.jpg</IMAGE>
<IMAGE TITLE="garden">image2.jpg</IMAGE>
<IMAGE TITLE="shop">image3.jpg</IMAGE>
</GALLERY>

As you just saw, 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. Another main feature of any XML document is that 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

Moving on the actual content within an XML file, each XML tag is called a node in ActionScript. The node may also have a node value specified between the tags of the node. Each node may contain a number of optional attributes that contain an attribute value specified within quotation marks. All of these parts could be seen in the generalized XML code below:

<ROOT-NODE>
<CHILD-NODE ATTRIBUTE="value">sub-child-node-or-node-value</CHILD-NODE>
<CHILD-NODE ATTRIBUTE="value">sub-child-node-or-node-value</CHILD-NODE>
<CHILD-NODE ATTRIBUTE="value">sub-child-node-or-node-value</CHILD-NODE>
</ROOT-NODE>

Our code above illustrates the three fundamental requirements for creating a valid XML file:

  1. The XML file must have ONE root level XML tag. In our example above it is <ROOT-NODE></ROOT-NODE>.
  2. Every single tag must be closed, either by using a closed version of the tag as shown in the example above (example </CHILD-NODE>), or by "self-closing" the tag by using the backslash at the end of the tag (not shown in the code above, example <NODE ATTIRIBUTE="value" />).
  3. If you are going to use an attribute (more on these in below), you will need to put its values within quotation marks.

Writing an XML File for Flash

XML is practically just made up of text and could be created using any text editor. Open your notepad and paste the code below to create your XML file, save it as oman3d.xml and put it in the same folder as your upcoming Flash movie.

<?xml version="1.0" encoding="utf-8"?>
<GALLERY>
<IMAGE TITLE="school">image1.jpg</IMAGE>
<IMAGE TITLE="garden">image2.jpg</IMAGE>
<IMAGE TITLE="shop">image3.jpg</IMAGE>
</GALLERY>
The first line of our XML code above is an optional parameter for setting the version of XML file we are using and the encoding of the file. Putting it is a good practice even though it does not make a difference to the code when working in Flash.

Loading XML in Flash

Start off by creating a new Flash movie in ActionScript 3.0 format. Right-click the only frame on the timeline and select Actions. The rest of our tutorial is going to be conducted on this window.

In order to load the XML data in Flash we need to do the following:

  1. Create a variable to hold an instance of the XML Class.
  2. Create an instance of the URLLoader Class to load the XML file.
  3. Pass the content of the XML file to the XML instance variable once the file has completed loading.
ActionScript 3.0 features another class for dealing with XML called XMLDocument. This class is identical to the old XML Class that is available for ActionScript 1/2. It is an alternative to the XML Class featured in this tutorial. Check to the ActionScript reference for more info on it.

We are going to do these one by one. We are going to start off by creating a variable to hold an instance of the XML Class. This can be done easily by using the var operator:

var myXML:XML;
The colon operator (:) is used to lock the type of the variable to XML. This means that this variable will not hold anything by XML data. Trying to pass any data type other than XML to it will create a compile-time error. It is used in the following generalized format: var variableIdentified:DataType;.

The next step is to create an instance of the URLLoader Class to load our XML file. The URLLoader Class is the class responsible for loading all binary and textual data. Once we create an instance of the URLLoader Class, we can use its .load method to load the XML file.

var myXML:XML;
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("oman3d.xml"));
The URLLoader Class needs the URL to be passed to it as an instance of the URLRequest Class. Refer to the ActionScript reference for more info on it.

That should pass the command for Flash to load the XML file. However, for us to process the XML file we must make sure that it has been fully loaded. To do that we need to create a listener that checks for the loading process to complete and then process the XML file. The listener is to be attached to our instance of the URLLoader Class in the manner shown below. Our listener will trigger the listener function processXML which will create in a short bit.

var myXML:XML;
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("oman3d.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
There are various events to which the a listener can be attached to. The different events available vary depending on the target object. For more information on the available events for the URLLoader Class check its entry in the ActionScript reference.

The code above will trigger the listener function processXML when the XML file finishes loading. We need to create the contents of this function, as specified in our procedure above, we need this function to assign the contents of our XML file as the XML data of our XML instance variable:

var myXML:XML;
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("oman3d.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
trace(myXML);
}
The reference to e.target in our code above refers to the object that loaded the XML file.

You can test your movie now to see the value of your XML file shown in the output window!

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 and the new E4X support for searching and accessing XML data.

The upcoming part of our tutorial will show you how to retrieve specific information out of the XML file using the various methods available to XML Class.

We are going to use E4X to retrieve the value of each of our XML nodes, get the value of a specific node, and then use it to retrieve XML node attributes.

First of all, if we would like to retrieve all the children of a node we can use the asterisk (*) operator.

var myXML:XML;
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("oman3d.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
trace(myXML.*);
}
The asterisk sign can be replaced by the .children() method which does the same exact thing.

We can alternatively select to pick only a certain selection of nodes, this will not make much sense in our code example because all of our child nodes are of the same type, but if we had different node types and we wanted only to retrieve a specific collection we can use the node name to retrieve them. For example, we can use the word IMAGE to retrieve IMAGE nodes only:

var myXML:XML;
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("oman3d.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
trace(myXML.IMAGE);
}
This should output the following when tested:

<IMAGE TITLE="school">image1.jpg</IMAGE>
<IMAGE TITLE="garden">image2.jpg</IMAGE>
<IMAGE TITLE="shop">image3.jpg</IMAGE>

To drill down and access the text value of each of of these nodes we have selected we can use the asterisk sign again this way:

var myXML:XML;
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("oman3d.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
trace(myXML.IMAGE.*);
}
This should output the following when tested:

image1.jpgimage2.jpgimage3.jpg

The result above is not really helpful, so what we need to do is retrieve the value of a specific node, to do that we can replace the asterisk sign with square bracket operator and a number indicating the position of the child in the XML file.

var myXML:XML;
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("oman3d.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
trace(myXML.IMAGE[0]);
}
This should output the following when tested:

image1.jpg
You should note that elements in an XML list are zero-relative. So the first item in the list is at position 0 and not 1. The second item is at position 1, the third at 2, and so on.

Retrieving the content of a node is pretty easy, retrieving the value of an attribute is not too hard either. To do that we simply use the @ sign along with the attribute name. This process can be used for a group of nodes or a specific node. For a group of nodes we can use this code:

var myXML:XML;
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("oman3d.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
trace(myXML.IMAGE.@TITLE);
}
This should output the following when tested:

schoolgardenshop

It can be used for a specific node by using the square operator and number this way:

var myXML:XML;
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("oman3d.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
trace(myXML.IMAGE[0].@TITLE);
}
This should output the following when tested:

school

The new XML controls in ActionScript 3.0 allow us also to filter our nodes by searching for attribute values and showing only the ones that correspond to our condition. For example, we can retrieve the value of the IMAGE node that has 'school' as its title:

var myXML:XML;
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("oman3d.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
trace(myXML.IMAGE.(@TITLE=="school"));
}
This should output the following when tested:

image1.jpg

A method worth mentioning is the .length() method, this method can be used to count the number of children a node has or a number of a specific type of children a node has. For example, to check how many IMAGE nodes are present in our gallery we can use the length() method this way:

var myXML:XML;
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("oman3d.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
trace(myXML.IMAGE.length());
}
This should output the number 3 when tested.

We can also easily count the number of all children in our XML file regardless of type by using the asterisk sign the same way we did earlier:

var myXML:XML;
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("oman3d.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
trace(myXML.*.length());
}
This should output the number 3 when tested.

I think that these are the most important basic essential tools needed for dealing with an XML file. You can review the ActionScript reference to learn about the other advanced tools. In the mean time, you can check the 'semi-practical' example shown below to see how XML is used in practice.

Semi-Practical Example

Our code extracts the contents of our XML file and displays 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;
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("oman3d.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
for (var i:int = 0; i<myXML.*.length(); i++){
trace("My image number is " + (i+1) + ", it's title is " + myXML.IMAGE[i].@TITLE + " and it's URL is " + myXML.IMAGE[i]);
};
}

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.