jump to navigation

Loading XML data using ActionScript 3.0 September 6, 2010

Posted by Tournas Dimitrios in Actionscript, Flash.
trackback

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.

Our tutorial will be divided into the following short sections:

  • What is XML?
  • Writing an XML File for Flash.
  • Loading XML in Flash.
  • 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.

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 ExternalFile.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 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.

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("ExternalFile.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.


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

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("ExternalFile.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("ExternalFile.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
trace(myXML.IMAGE.*);
}

/*
Note : 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("ExternalFile.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
trace(myXML.IMAGE[0]);
}

/*
Note: 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("ExternalFile.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
trace(myXML.IMAGE.@TITLE);
}
/*
Note: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("ExternalFile.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
trace(myXML.IMAGE[0].@TITLE);
}
/*
Note: 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("ExternalFile.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
trace(myXML.IMAGE.(@TITLE=="school"));
}
/*
Note : 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("ExternalFile.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
trace(myXML.IMAGE.length());
}

/*
Note : 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("ExternalFile.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
trace(myXML.*.length());
}

/*
Note : 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 :

var myXML:XML;
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("ExternalFile.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
for (var i:int = 0; 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 …….

Advertisements

Comments»

No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s