Tutorials Books Videos Forums

Change the theme! Search!
Rambo ftw!

Customize Theme


Color

Background


Done

Introduction to XML in Flash: Finding Your Way Around An XML Object

by senocular   | filed under Web, HTML, CSS, and XML

This is an archived tutorial from the kirupa.com legacy collection. It covers software that may no longer be available, but it is kept online because the ideas still hold up.

Once you know (or think you know) what is what in a Flash XML instance, it's time to figure out how to extract that what so that you can use it for your evil conquests of world domination... and... other Flash needs too. Navigating an XML object can be just as hard, if not harder, than simply understanding its structure. Though once you understand the structure, navigation becomes a bit easier.

Because arrays are used heavily in storing elements, looping will start to become your favorite pastime when working with XML. Loops (for and while) in Flash allow you to easily cycle through all elements of an array, or, in the case of XML, all the children of an element, allowing you access each one of those nodes individually within each iteration of the loop. Depending on the structure of your XML, for loops may need to be nested in order to loop through elements within elements already being looped through. That's always fun right?

Note: Design XML for Accessibility

If you are in direct control of the structure of your XML file, you may want to try, if possible, to minimize the number of levels in the XML hierarchy. The fewer nested loops you need to implement, the better. There are other ways around nested loops which will be brought up later. But it's important that if you are designing XML to be used primarily in Flash that you design it to be easily navigable.


Navigation Through Helpful XML Properties

So far we've seen that XML nodes in Flash form have attribute objects and child nodes arrays stored as properties represent their structure. Flash ActionScript provides some additional properties added to XML nodes to help make navigation through it a little more easier. Here's a list of XML structural properties you can reference off of XML nodes.

Property Represents
XML Nodes
attributes An object containing attribute variables assigned to this element.
childNodes** An array containing all child nodes belonging to this node.
parentNode* This node's parent node.
firstChild* The first child in this element's childNodes,
or childNodes[0]
lastChild* The last child in this elements childNodes,
or childNodes[childNodes.length-1]
nextSibling* The node after this node in the parent's childNodes array.
previousSibling* The node before this node in the parent's childNodes array.

*Read-only and can only be checked, not directly set.
**Altering element order in this array will not be reflected in the XML instance.

Together, these properties provide the groundwork for you being able to navigate through your XML.

Of course seeing the properties, and reading and understanding what they represent is one thing. Being able to use them is a whole new slice of cheese. Making proper use of these properties is really what makes XML so difficult to deal with in Flash. We'll work through a little of that now but the Flash examples given later on will provide a better understanding of using them more effectively and in context.

The first thing to remember is that an XML instance represents a single node in which the rest of the XML is defined. That means that your XML instance and the document root node of your XML are not the same thing. The root node is actually a child of the XML instance. Since there should be only one root node (DOCTYPE and XML declarations are not considered nodes and are not accessible as children), that means your root node would be the first child of the XML instance. Given the XML instance my_xml, the root node would be:

my_xml.firstChild

From here, you can then start accessing your XML as needed.

Now, you'll notice that even just getting to the document root of an XML document through an XML instance requires using firstChild. What do you think happens when you want to get to the first child of the first element in your document root? Consider the following XML:

<mydocuments>
  <mypictures>
  <family>
  <image title="Sister laughing" />
  <image title="Brother laughing" />
  <image title="Mother beating me" />
  </family>
  <vacation location="Myrtle Beach">
  <image title="Sun bathing" />
  <image title="Walking the dog" />
  <image title="Swimming" />
  <image title="Getting eaten by shark" />
  </vacation>
  <girls />
  </mypictures>
</mydocuments>

Now assume this is the XML content of the my_xml variable in Flash. The first child of the first element in the document root is family (where mypictures is the first element in the document root). So, in order to reach the family node in my_xml, you would use:

my_xml.firstChild.firstChild.firstChild

Already you can see the complexity and confusion that's just starting to unravel. If it takes that much just to get to the first pertinent element in a simple XML document such as the one above, imagine the paths needed to get to things in a more complicated XML document. How are you ever to keep track?

Variables. Variables are the key to success and understanding when using XML. Variables and loops. Looping gets you through element children and variables provide you a way to give descriptive names to abnormal paths such as the one given above. What's easier to understand? my_xml.firstChild.firstChild.firstChild.firstChild or family.firstChild? Saving the original path in a family variable (as it represents the family element) you get yourself a clearer understanding in the reference to the specified image element.

When using loops, you would typically use the childNodes array. Then, just like with any other array, you would loop through each element performing whatever task is needed on each. For example, to loop through all the image elements in vacation, you could use:

var family = my_xml.firstChild.firstChild.firstChild;
var images = family.childNodes;
for (var i=0; i<images.length; i++){
  currImage = images[i];
}

Using the attributes object, you could then access the titles of each and trace them in the output window

var family = my_xml.firstChild.firstChild.firstChild;
var images = family.childNodes;
for (var i=0; i<images.length; i++){
  currImage = images[i];
  trace(currImage.attributes.title); // trace each images' title
}

Lets say you then wanted to go about looping through the vacation images. How might you go about that? Well, you could use a similar path to get to vacation as you did with family. Only with vacation, the last child reference would have to be from the childNodes array since vacation is neither the firstChild nor the lastChild of mydocuments.

var vacation = my_xml.firstChild.firstChild.childNodes[1];

However, since family has already given us much of that path already, nextSibling can be used to get to vacation directly from family.

var vacation = family.nextSibling;

Unlike the child reference properties, the sibling properties stay within the same element scope being able to reference other nodes which share the same parent (in this case mypictures) as the node from which its being used. So, after going through the family image elements, you can go through vacation images using:

var vacation = family.nextSibling;
var images = vacation.childNodes;
for (var i=0; i<images.length; i++){
  currImage = images[i];
  trace(currImage.attributes.title); // trace each images' title
}

The following provides a more visual representation of what each property represents in regards to a vacation node within in an XML file.

[ xml references in respect to the vacation element ]

You can see that the vacation node has a wide array of direct access when it comes to referencing other nodes within the XML in respect to its location using those properties available to it. The parentNode property references mypictures, the element in which it exists; previousSibling and nextSibling references the child nodes next to vacation within that parent node on either side of itself (a.k.a. "siblings" like brothers and sisters). We saw how family's nextSibling was vacation. Using vacation's previousSibling, you can go back up to family. And then of course you have firstChild, childNodes, and lastChild provide access to vacations own children, its image elements. Parents, siblings, children, XML just asks to have a family tree written in it, doesn't it?

There are yet some other properties which you can use to find out more about your XML and its nodes. These don't necessarily help you navigate through your XML so much, but they provide important information nonetheless. They are as follows:

Property Represents
XML Nodes
nodeName The node's name. This is the tag name of an element node and null for other nodes.
nodeType*

A numerical value representing the node's type:
1 = Element
3 = Text Node (or CDATA Section)

nodeValue The node's value. This is text for text nodes and CDATA and null for elements.
XML Instances
xmlDecl XML's declaration
example: <?xml version="1.0"?>
docTypeDecl XML document DOCTYPE declaration
example: <!DOCTYPE greeting SYSTEM "hello.dtd">
loaded True or false depending on whether or not the last load() command has successfully completed for the XML instance.
status

A numeric value representing parsing errors during Flash 's attempts to convert XML text into the ActionScript XML object. They are as follows:

0 No error; parse was completed successfully.
-2 A CDATA section was not properly terminated.
-3 The XML declaration was not properly terminated.
-4 The DOCTYPE declaration was not properly terminated.
-5 A comment was not properly terminated.
-6 An XML element was malformed.
-7 Out of memory.
-8 An attribute value was not properly terminated.
-9 A start-tag was not matched with an end-tag.
-10 An end-tag was encountered without a matching start-tag.

*Read-only and can only be checked, not directly set.

We've already seen nodeName and nodeValue before, but nodeType is a new one. It helps you distinguish elements from text nodes. Other properties listed are for XML objects specifically and not the nodes they contain. The first two, xmlDecl and docTypeDecl let you extract an XML document's declaration and doctype which are not, technically, otherwise included as elements in the XML structure (at least not in Flash). The other two, loaded and status, just help determine information about loading and parsing XML, whether or not they were successful.

With all these properties out of the way, we can start getting into some examples which make practical use of them, hopefully in a comprehensible manner.


Evaluation: XML And Your Family Tree

I've been ranting on an on throughout that XML seems fit for a family tree. Parents, children, siblings - XML just seems so very family oriented. But is that really the case? Lets take a closer look at how elements in an XML hierarchy are arranged and whether or not they make presenting a family tree easy.

Way back when, the file-folder analogy was used to help describe the structure of XML. You have folders (elements) and in those folders you have files or more folders (elements and other child nodes). Any single folder can have any number of files or folders and any of those folders within a folder can have their own similar collection and so on. A file or folder, however, only exists in a single folder at any given time. You get a relation that looks like this:

[ general structure of xml ]

Because everyone can relate to their family and know who's who (who's a parent and who's a child), keywords used to describe similar relations are used to make using XML more comprehensible - child nodes, parent node... siblings, etc. However, if you think about it, they aren't quite exactly the same. There's one key difference in the real family structure when compared to that of XML. That difference is having two parents. Look at the following. It represents a portion of the family structure of a single person (subject)

[ structure of a family tree ]

Here, the subject belongs to two parents, a mother and a father. The children belong not only to the subject, but also to the subject's spouse. So the children, too, have more than one parent. Like with files and folders, this just isn't possible with XML (that's right, XML does not support multiple inheritance). This doesn't, however, make an XML version of a family tree impossible. It just makes it so that an XML representation will not structurally match the content it contains. And there's nothing wrong with that. It's perfectly fine but it also means that interpreting that information will might take a little more effort.

An example would be... wouldn't you know it, FTML. Yup, Family Tree Markup Language - XML for family trees (FTML is technically based off of SGML like HTML and XML). FTML uses id attributes to manage and relate people to other people as they are linearly listed within a FTML document. Take a look at this quick example:

<?xml version='1.0'?>
<!DOCTYPE ftml SYSTEM "ftml.dtd">
<ftml>
  <people>
  <person id="Granddad" sex="male" surname="Example" forenames="Granddad">
  <born date="1915" />
  <died date="1998" />
  </person>
  <person id="Grandma" sex="female" surname="Jones" forenames="Granny" />
  <person id="Dad" sex="male" surname="Example" forenames="Daddy">
  <born date="1940" />
  <mother id="Grandma" />
  <father id="Granddad" />
  </person>
  <person id="Mom" sex="female" surname="Smith" forenames="Mommy" />
  <person id="Uncle" sex="male" surname="Example" forenames="Uncle" />
  <person id="Aunt" sex="female" surname="Trotter" forenames="Aunt" />
  <person id="Me" sex="male" surname="Example" forenames="Me">
  <born date="1973" />
  <mother id="Mom" />
  <father id="Dad" />
  </person>
  <person id="Brother" sex="male" surname="Example" forenames="Brother">
  <born date="1971" />
  <mother id="Mom" />
  <father id="Dad" />
  </person>
  </people>
  <marriages>
  <marriage husband="Dad" wife="Mom" date="1964" />
  <marriage husband="Uncle" wife="Aunt" />
  </marriages>
</ftml>

All people within this family structure here are listed linearly in the people element. Each person is given an id which is then referenced in two places: 1) in the person definition where a mother and/or father is specified and 2) in the marriages section where a husband and wife are connected by id (some versions of xml-based family trees keep marriage relations within the person tag under wife or husband).

So, the best use of the XML hierarchy within this document is just maintaining content concerning a single person (and the collection of people). Actual relations are all handled through ids. So despite my hopes in creating an example based on a family tree, given the type of XML design needed above, that's not something we're about to tackle here. Lets continue with another, simpler example. For your own XML projects, however, you may need to consider a setup something similar to FTML. Something to keep in mind.


That wraps up this tutorial. A huge thank you to all of you who buy kirupa's books, became a paid subscriber, watch the videos, and/or interact on the forums. Your support is what keeps writing like this online! 😇

senocular

This tutorial was written by senocular, also known as Trevor McCauley. He has been one of this community's most generous teachers since the early Flash days, and he is still around: find him on senocular.com and on the forums.

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2026 //--