Tutorial details:
Written by: Jesse Stratford
Time: Approximately 1 hour
Difficulty Level: Intermediate
Requirements: Flash 5 or higher. Text editor. Some code may work only in MX.
Topics Covered: XML from the ground up. What is it, when to use it, how to use it and more!
Assumed knowledge: Paths, Variables, arrays, Scripted Loops, basic Object Oriented Principles.

Grab the source files to all the examples used in this tutorial right here.

First off let me say that XML, being a data structure is a broad topic. This tutorial will teach you how to load, format and use XML documents in Flash to a certain degree. Being a tutorial for intermediate level users I'll work on the assumption that you have a good understanding of the Flash environment, and a fairly good understanding of ActionScript, but I'll try to make it as painless as possible! For this reason this tutorial has turned out pretty long, so if you already know a bit about XML you might want to use the subheadings to skip the stuff you know and get down to the nitty-gritty.

What is XML?
"Assume no prior knowledge", I say to myself. If you've been living under a rock and have never heard of XML, then let me be the first to welcome you back from your solitude!
For our purposes XML (which stands for eXtensible Markup Language) is a way of structuring, arranging and representing data. One of the benefits of XML is that it allows for customizable and neat representation of data which can be easily parsed (interpreted by a computer) while at the same time being clearly readable to a human.
Before I continue, when reading the next section keep in mind that XML is easy-peasy, so don't let the concepts or tech terms scare you. Keep reading and you'll get it.
XML uses 'tags' (similar to HTML tags) which may or may not include refining elements called 'attributes'. (Since most people know some HTML this is a good example to use but don't get carried away with the similarities: HTML is primarily a markup language, while XML – in relation to Flash at least – is primarily a data structure.) Consider the HTML bold tag – to create some bold HTML text we use:

<b>This is some bold text</b>

The simple 'tags' at the beginning and end of the text string tell the browser to format that string in a particular manner. XML is similar to the extent that it too uses such tags in its structure, however in XML, instead of being a way of describing the visual representation of data, tags are used to group related pieces of information into 'nodes'. In fact the above snippet is a properly formatted XML node. This will get easier with an example, (below), but let me just pound you with one or two more tech terms first. Nodes are hierarchical, that is, they can contain other nodes within them ('child nodes'), and their children can contain children, just like MovieClips in Flash (see my Paths tutorial). XML is also associative in that two nodes which are children of the same parent node are recognized as being siblings.
XML, unlike HTML, is extremely touchy when it comes to formatting. An XML document must strictly conform to various rules in order to be processable: this is a good way to enforce clean coding. The rules are as follows:
All nodes (except self-contained nodes which we may discuss later) must have a beginning and ending tag, which are alphanumerically identical. That means tags are case-sensitive, for instance this is valid:

<authorName>Jesse Stratford</ authorName>

But this is not (note the lack of capitalization in the closing tag):

<authorName>Jesse Stratford</ authorname>

Also note that the space after the slash and before the node name in the closing tag is optional.

Nodes which contain nodes must also be closed in the correct order. Consider a box which contains another box. You open the outer box, open the inner box then place something (a cake . . . mmm cake) inside the inner box. Now if you try to close the outer box without closing the inner box, the lid won't go down because the inner box is still open. The same applies for XML, so this is valid:

        <innerBox>Cake</ innerBox>
</ outerBox>

But this is not

        <innerBox>Cake</ outerBox>
</ innerBox>

While this might seem obvious, such rules are often broken in HTML and it's important to get them out of your system now rather than at 1am one night with a deadline looming when you're running around the house, screaming and trying to figure out why your XML isn't working. Don't say I didn't warn you!

Why and when to use XML?
Honestly, I don't know. I think it's because Microsoft are pushing it and small-business people know their competitors are using it, so it must be good. Seriously though, XML is a very useful method of representing data and it's very much the way to go with Flash, but it has its problems like everything. One of the biggest dangers is massively verbose XML tags. The ability to create your own tags in XML means that XML documents can be self-documenting to a certain extent, but some developers may be drawn into abusing this feature and get into using extremely long XML tag names, for instance:

        <whatUsersWhoHaveReadThisBookThinkAboutIt>...</ whatUsersWhoHaveReadThisBookThinkAboutIt>

Don't laugh; I've seen it happen! The nature of this structure is fine, but the child node would of course be much more easily represented by a 'reviews' node, or something much shorter. The longer your tags are, the more bytes your clients are going to have to download, and that equates directly to them spending more time waiting for your site to load, which we all know is a bad thing.

For this same reason, there are many instances where XML is simply not necessary. For instance, if you have a backend script which hands out the password for the day to various users, you might as well just send it back as a text string, instead of an XML document with one node. The tags would just be useless bytes and the new LoadVars Object contains most of the useful methods that are applicable to such a system.

For many other applications, XML is the way to go. A great example can be found at Amazon.com who recently opened up the back-end databases (through Web Services 2) to the general public. Using the correct protocols you can send a key word query to Amazon and it will return information on all relevant books in XML format. The document contains a list of books, each of which contains child nodes telling you everything from the author of the book to the average rating from Amazon.com reviewers. It's great and a very suitable application for XML and Flash.

Loading XML into Flash
Well that was a long but necessary preamble; now let's get into actually using XML in Flash. First we will need an XML document to work with, so let's start small. Below I've made up a small XML document (download example1) which includes just one node:

<author>Jesse Stratford</ author>

I save this in a text file (using a compatible text editor such as Notepad or similar), as author.xml. Next, I fire up Flash MX and create a new document 'author.fla', which I save in the same directory as my new XML file.
Within Flash we need to create a new XML object into which we are going to load our external XML file.

tuteInfo_xml = new XML();

Note that I added '_xml' to the end of my XML Object's name so that the ActionScript panel will automatically recognize this Object as being and XML object and provide me with a dropdown of the appropriate methods whenever I refer to it.
With our new object prepared we can load in our XML:


When working with XML, Flash provides methods which are automatically invoked when certain evens occur, such as when a document we try to load finishes loading. This means we don't need to constantly check if our data has finished loading, we simply define the actions we wish to take place in a function which is invoked by the load event handler, as follows:

tuteInfo_xml.onLoad = function (success) {
        if (success) {
                trace('Author.xml loaded. Contents are: '+this.toString());

This code creates a new function which is invoked when the XML document is loaded. The function is automatically passed the success argument, a Boolean value which indicates whether or not the document loaded successfully (this is a built in function of the onLoad event handler in Flash). If the load was successful, I trace a small message for debugging purposes, which outputs the following:
Author.xml loaded. Contents are: <author>Jesse Stratford</author>

Note that it is common practice to insert the onLoad function definition above the load command but it must go after the creation of the new XML object, thus it is most commonly put between the object declaration and the load command.

Before we continue, I should point out that in the above example, the fact that the XML document is just one line with no trailing blank space is important. Most XML documents you will work with will be formatted using new-line characters, tabs, etc. in order to make them more presentable and human-readable, in such cases it is important to tell Flash that your XML document will contain unimportant whitespace, otherwise Flash will not handle it. This is done by setting the ignoreWhite property of your XML object to true, for example:

tuteInfo_xml.ignoreWhite = true;

So the entire code snippet for our simple example above is:

tuteInfo_xml = new XML();
tuteInfo_xml.ignoreWhite = true;
tuteInfo_xml.onLoad = function(success) {
        if (success) {
                trace('Author.xml loaded. Contents are: '+this.toString());

But loading is just the beginning, turn the page to continue!