Mar
18
2010

 

XML support was first added to Flash 5, it was not supported on Flash 4.  This tutorial explains how a Flash movie can retrieve (load and access) data from an external XML file using Action Script 3.  If you are used to the complicated way of parsing XML in Action Script 2, you will be delighted with how much easier it is to do the same things in Action Script 3.

ActionScript 3 includes supports for E4X (ECMAScript For XML), which makes working with XML much easier than in ActionScript 2. The Action Script 2 version of this tutorial is here (there is no need to read it unless you are still using Action Script 2): http://permadi.com/blog/2009/09/flash-as2-reading-xml-file/

BACKGROUND

Why would there be a need to read from a file?  Suppose you have a movie that displays a “news of the day.”  You could put the content of the news on the swf file, but if you do so, every time the news changes, you’ll need to edit the Flash file.  That’s very impractical.  So the benefits are: 1) To save time (avoid editing and recompiling of the Flash file); and 2) to separate your application from the data (encapsulation, implementation hiding).

You can use regular text file to pass external data – see here.
Yet another way to pass external date is to embed the data using the query string or using FlashVars.


Why use XML? The benefit of using XML is that you can format the data more elegantly; and also, since XML has been widely used nowadays, the exact same XML file could potentially be used for other purpose.  Since XML is very good for representing hierarchical form of data, so you avoid the messy format required by using the other file format.

REQUIREMENTS

To understand this tutorial, it’s recommended that you know:

  • How to access variables in Flash via a textbox.
  • Some general Flash Action Scripting knowledge and syntax.
  • Some basic XML knowledge (hierarchical structure, formatting).
  • Basic E4X (for references, see here: http://en.wikipedia.org/wiki/ECMAScript_for_XML).

This tutorial is written in Flash CS3.  The sample project can be downloaded at the end of the tutorial.

A SAMPLE XML FILE

For this tutorial, we are creating a sample XML file that holds “news of the day” mocks.  It is not necessarily the best way to represent a news item, but it will do for illustration purpose.  The XML file to be used in this tutorial is called “news.xml”  It can be downloaded here: news.xml.  The structure of the XML file is shown below.  Note that we’re not using a DTD because Flash will ignore it anyway.

[c]<?xml version="1.0" standalone="yes"?>
    <news>
         <header>Vacation is Good</header>
         <content>Scientists recommend a full month of nice vacation for people who are bored.</content>
         <info more_info="www.permadi.com">
                <comment>No comment</comment>
                <author>F. Permadi</author>
         </info>
    </news>[/c]

Note that:

  • the root node of the XML file is <news>.
  • A <news> node contains a <header>, a <content>, and an <info> element.
  • An <info> node itself has a “more_info” attribute, and contains a <comment>node and an <author> node.

Note about XML editingSome characters are ‘special’ because they can be confused as XML markups, therefore they need to be written differently.  If you use one of the special character below, you should use the name entities:

Symbol Name Entities
> &gt;
&quot;
&apos;
& &amp;
< &lt;

For example, to replace the <header> with “Vacation is Good & Healthy” then you should not do this:
<header>Vacation is Good & Healthy</header>

Instead, use the special character notation like below:
<header>Vacation is Good &amp;Healthy</header>

Or, alternatively, you can enclose the text in something called CDATA, like below:

<header><![CDATA[Vacation is Good & Healthy ]]></header>

CREATING THE SKELETON FLASH MOVIE

Let’s start with a sample Flash movie.  This movie will display a “news of the day” movie using data from the above XML file.  Here’s what frame 1 looks like:

The movie has 4 textboxes which will be used to display text that we read from the XML:

  • the one which shows “header”
  • the one which shows “Loading data…”
  • the one which shows “author”
  • the text “My News Page” is a static textbox (we’ll not be doing much with this particular textbox)

The “header” textbox is named “header” and this box will hold the <header> node.

Just for illustration purpose, I name all the text-boxes the same as the XML nodes.  PS: Make sure that this button is off so that user can’t select (highlight) the text.  It will look weird if you allow user to select the text.

The center text-box is named “content“.

The “author” textbox is associated with Var: author.
This box will hold the name of the <author> node.

We’ll ignore the other XML elements such as <date> and <comment> for now.

LOADING THE XML FILE IN FLASH

Below is the code that loads the XML object.  You can add this code to the Frame 1 of the FLA main timeline.

[c]
var urlLoader:URLLoader=new URLLoader();
urlLoader.load(new URLRequest("news.xml"));
urlLoader.addEventListener(Event.COMPLETE,onXMLFileLoaded);
stop();
[/c]

We are using the URLLoader class to load the file.  The parameter “news.xml” is the filename to load.  Note that the file can be on a different folder or a different server (if the file is on a different server, the other server must have a cross-domain policy that permits you to load the file.  Read more about cross-domain policy on the Macromedia site.

It is worth noting that when you load external file like this, you should not assume that the file is loaded immediately.  Because Flash does not know how large the file is, it runs the process in the background while the movie continues to run.  However, Flash is thoughtful enough to notify us when the file has completely loaded by sending an event.  In the URLLoader the event is Event.COMPLETE.  In the example above, we associate the function named onXMLFileLoaded with that event.

Below is the code with onXMLFileLoaded added.

[c]
var urlLoader:URLLoader=new URLLoader();
urlLoader.load(new URLRequest("news.xml"));
urlLoader.addEventListener(Event.COMPLETE,onXMLFileLoaded);
stop();

function onXMLFileLoaded(event:Event):void
{
  var myXML:XML=new XML(event.target.data);
  // the XML data is ready to use, do something with it.
}
[/c]

Note that in this line:

[c]var xml:XML=new XML(e.target.data);[/c]

we simply assign the data loaded (which is in event.target.data) into an XML object named myXML. Now we can start accessing the data on the XML.

PARSING THE XML FILE

For illustration purpose, let’s print the content of myXML, we can do this by setting the textbox to display the content of myXML like below:

[c]
function onXMLFileLoaded(event:Event):void
{
  var myXML:XML=new XML(event.target.data);
  content.text=myXML;
}
 [/c]

You should be seeing the xml content printed on the textbox.  It’s not nicely formatted yet, but it’s a start.

If you run the debugger, you can see the myXML object looks like below:

According to the diagram above, myXML has 3 child nodes. We already know from the XML file that the
node should have 3 child nodes (header, content, and info). Let’s extend the tree view and see.

A node can only have one parent, but a parent can have multiple children. In the example above, parentNode has 3 child nodes.
<parentNode>
<childNode1>Child 1</childNode1>
<childNode2>Child 2</childNode2>
<childNode3>Child 3</childNode3>
</parentNode>

To access nodes, we can refer to them by the node names or by using the member functions of the XML class. A complete reference of the XML class can be found here: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/XML.html

Let’s focus on some of the important functions.

  • To access the children of a node:
    children():XMLList
  • To access attribute of a node:
    attribute(attributeName:*):XMLList
  • To access attibutes of a node:
    attributes():XMLList

Some of the functions returns an XMLList object, which is basically a collection of XML objects.

For illustration purpose, let’s list the children of our myXML example, using this command:
myXML.children();

[c]
function onXMLFileLoaded(e:Event):void
{
	var myXML:XML=new XML(e.target.data);
	content.text="Child 0 is " +myXML.children()[0];
	content.text+="\n\nChild 1 is " +myXML.children()[1];
	content.text+="\n\nChild 2 is " +myXML.children()[2];
}
[/c]

The output is

The order is always the same as in the XML file. So, children()[0] is for <header>, children()[1] is for <content>, and children()[2] is for <info>.

To do the same thing using E4X, we can refer to the node names like below:

[c]
function onXMLFileLoaded(e:Event):void
{
	var myXML:XML=new XML(e.target.data);
	content.text="Child 0 is " +myXML.header;
	content.text+="\n\nChild 1 is " +myXML.content;
	content.text+="\n\nChild 2 is " +myXML.info;
}
[/c]

You can see how easy it is using E4X, assuming you already know what to expect in the XML.

Continue to Part 2.

Comments are closed.