Flash Kid Logo  
Home - Tutorials - Applications - Games - Community - Site Map - Contact Us  
 
 
 
 
 
Using XML in Flash Tutorial
Author: Salman Awan
Difficulty Level: Advanced
Flash Version: Flash MX 2004
Sources to Download: using_xml_in_flash_tutorial.zip
 
Bookmark This Page
Prerequisites: ActionScript Basics, HTML Basics, Object Oriented Programming

Introduction:
Flash MX 2004 supports reading data in XML format. This Flash XML tutorial will be helpful in getting you started with basics of using XML in flash. In this tutorial we will focus on possible usage of XML in flash rather than to provide a detailed introduction of XML.


XML is very easy to grasp, you can proceed with this tutorial even without any prior knowledge of it, however if you need to get an in-depth understanding of XML concepts, you can refer to tutorials at W3Schools.

Brief Introduction of XML:

eXtensible Markup Language (XML) can be termed as a way of transmitting information. XML itself does not do anything, unlike HyperText Markup Language (HTML) which is designed to display data and to focus on how data looks, XML is designed to describe data and to focus on what data is.

In XML, we format our Information between our own defined Tags, while sticking to few, but strict XML rules. Thus XML is in effect a string of Tags & Information formatted based on some rules.

One very simple example of valid XML is displayed below:

<Contact>
            <Name>Salman Awan</Name>
            <Email>my email</Email>
</Contact>


Here XML defines a Contact that holds Name and Email information.

Rules of writing XML:
Writing XML is as easy as writing a string of Tags & Information in Notepad, following these few basic rules:

1. All XML Elements Must Have a Closing Tag - Any opening tag must have its corresponding closing tag e.g. </Contact>, </Name> & </Email> in above example.

2. XML Tags are Case Sensitive – Meaning <Contact> is different than <contact> thus it must have a closing tag of </Contact>

3. XML Elements Must be Properly Nested – A tag which is opened last must be closed first. In HTML this might not be a strict rule, but in XML it is, to ensure a proper hierarchy. For example this is an incorrect XML:

<Contact>
<Name>Salman Awan</Contact>
</Name>

 

4. XML Documents Must Have a Root Element – In our example <Contact> is the root element.

When to Use XML with Flash:
Sometimes while creating a Flash application, we need to provide user some flexibility to customize Flash widget without messing up with ActionScript itself, thus we expose all such customizable properties through XML to ensure user can change input parameters, while sticking to our predefined data structure. XML Flash Slideshow can be one example, where we can read ‘image pause time’ as a property in XML. Thus enabling user to customize flash application without recompiling and changing code.

Flash XML mp3 player can be another implementation, where list of songs can be read from an XML file, thus enabling user to change song Titles & locations, and even increase/decrease number of songs.

Creating an XML file:
We will now create an XML file which we’ll then read through Flash and display its data. For this, open up Notepad and paste XML below in it. Save this file as “Library.xml”

Tip: you might need to save with double quotes and specify All Files while saving XML file.

<Library>
            <Book id="1">
                        <Title>Using XML with Flash</Title>
                        <Authors>
                                    <Author>Salman Awan</Author>
                                    <Author>Christina Ray</Author>
                        </Authors>
            </Book>
            <Book id="2">
                        <Title>Book 2 Title</Title>
                        <Authors>
                                    <Author>Single Author</Author>
                        </Authors>
            </Book>
</Library>


This file defines data structure of a simple library, with multiple books. Each book has a title and multiple Authors.

Viewing XML Files in Browsers:
To test your XML file, open up your browser e.g. IE or Mozilla Firefox, drag and drop your newly saved XML file in it. The XML file will be displayed in default colorings and with plus (+) or minus (-) against Nodes.

XML displayed in Mozilla Firefox
Fig. 1 - XML displayed in Mozilla Firefox

If we closely examine XML files, they actually form a hierarchical tree, with its Elements as Nodes of the tree. It would be helpful for you if you start visualizing your XML documents in hierarchies e.g. Our Library example can be visualized as:

Visualizing XML as an hierarchical tree
Fig. 2 - Visualizing XML as a hierarchical tree

Creating Flash File for Reading XML:
Open a blank Flash document and save it in same directory as of XML file. In ActionScript panel enter following line of code:

library_xml = new XML();

Here we have created an object of XML Class that is predefined in Flash ActionScript. Functions & Properties provided in XML Class will help us in parsing XML tree.

Let’s set an attribute ignoreWhite to true so that any white spaces between Elements and Values are ignored. Also if there is any blank Element without value, it will be ignored.

Add this line under existing line of code:

library_xml.ignoreWhite = true;

Now we are all set to load XML data in our XML Object. For this purpose we will use load method of XML Object.

Add this line of code under existing code:

library_xml.load('library.xml');

If we now try run our application, nothing will happen, however in background XML might have been loaded successfully in XML Object. To test whether XML is loaded successfully and when it is loaded completely, an event onLoad is provided.

Add below event call under existing code:

library_xml.onLoad = function (success) {
        if (success) {
             trace( this.toString() );
        }
};

Tip: see source code of this tutorial for detailed comments on each line of code.

Accessing Node Values:
Now when you will try run application within Flash authoring environment, it will trace out complete XML read from library.xml file as a string.

This is good, but not good enough, we need to be able to access individual values within this XML object. Replace above trace statement with this one:

trace( this.firstChild.firstChild.nextSibling.firstChild.nextSibling.firstChild.firstChild.nodeValue );

see below figure for step by step parsing of this long reference. Here this is reference to our XML Object, and its first child is root element, Library.

nextSibling points to immediate next child of same parent, thus nextSibling for first Book is second Book (step 2 & 3)

Step by Step parsing of XML tree
Fig. 3 - Step by Step parsing of XML tree

Note: It is very important to note that Values of Tags are saved as separate virtual Nodes, see step 7 in above figure. And to access actual value of that virtual Node, you need to use nodeValue property (step 8).

Accessing Attributes:
You might have noticed id attribute in each Book’s node. Assigning Attributes to Nodes is another method of attaching values. These values must be enclosed in double quotes. We can access these values in slightly different way.

Replace above trace statement, in onLoad Event, with this new line:

trace (this.firstChild.firstChild.attributes.id);

This line of code will print out id value of first Book i.e. “1”.

Note: All attributes of a Node are saved in an object named attributes and they can be accessed with same names as defined in XML file.

Exercises:

  1. Create a trace statement for displaying first book's Title value.

  2. Create a trace statement for displaying first book's second Author using lastChild property.

  3. Add more books in XML file, trace Title value of third book.
  1.  Try filling XML values in an Array of Objects.

  2. Create a flash application displaying all Book Titles in a drop-down list.

 
 
 
 
Related Links
Discussion Forum for Using XML in Flash Tutorial
 
 

 
 
 
© 2008 flashkid.org! All Rights Reserved.