Extensible Markup Language (XML) is a popular standard developed by the World Wide Web Consortium (W3C). XML is an open architecture designed to allow the interchange of data between any platform or language on the Internet. The technology has caught on like wildfire, and you would be hard pressed to find any current application that doesn't use XML in some way or other. The complete XML specifications are available here.
In support of the standard, Macromedia has added XML functionality to the Flash Player. Why would you want to load XML data into Flash? There are several advantages. First, Flash has the unique ability to process XML on the client side on almost any platform. Typically, most XML transformations are handled on the server side because browser support for XML is sporadic at best. Second, Flash can seamlessly combine XML data with cool animation and sound.
The XML object also extends the functionality of Flash. URL-encoded query string variables are traditionally used to bring data into a Flash movie via the Load Variables function. Here is an example of a typical query string used in Flash:
Most browsers are limited to a header size of approximately 256 characters (including query string data). The XML object has no such limitation. This makes it an ideal method for bringing database content into your Flash movies. On top of that, the XML object allows you to import and integrate any XML-formatted data available on the Web into Flash.
The Flash XML object gives you all the tools necessary to bring in, parse, manipulate, and export XML-formatted data. The XML object API is well documented and available on the Macromedia Web site.
Download the code
You can download the sample code for this article here.
Loading the XML file
Before you start adding code to a Flash movie, it's a good idea to create a unique layer for your ActionScript. I typically create a layer for all elements of my Flash movie (Figure A) because it makes it much easier to isolate and troubleshoot problems later on.
|Put elements in different layers|
The next step is to create an instance of the XML object and load in the XML file. You can do this with two lines of code:
cnetXML = new XML();
If you look at the Flash XML API, you will notice a function called parseXML. You will hardly need to use this function; parseXML is automatically invoked by load().
Keep in mind that if an external XML file takes more than 15 seconds to load in Flash, it will time out. In other words, it simply won't load—the Flash Player and your movie will stop dead in their tracks. Also, loading in 64K or more of data using the load or sendAndLoad actions can cause performance issues in your browser. Symptoms include the server responding with "Error 501-Not Implemented" or general browser unresponsiveness.
Unfortunately, there is not much you can do about this except make smaller XML files. Loading in segments of data across many frames will help the browser parse the information bit by bit and increase browser performance overall.
The Flash Player also can't load in XML files from external Web sites. A Flash movie can load in XML only from its own domain. For example, a Flash movie residing on somedomain.com can't read or load in an XML file from cnet.com.
To get around this limitation, you can use middleware such as Coldfusion, ASP, PHP, or even Java to load data from another domain. The key is creating a dynamic page that will pull in and output data from an external source. Since the page will reside on your server, the domain restriction will be bypassed. Here's how you can pull this off in PHP:
Macromedia has documented this limitation and provides free source code to get around the problem.
Coping with white space and boosting performance
Some versions of Flash Player have a known bug: White space or carriage returns can be interpreted as nodes, most notably in Flash Player version 22.214.171.124 and later versions of Flash Player v.5. To correct the problem, Macromedia has devised the ignoreWhite function to explicitly tell the player how to cope with white space. To invoke the function, you simply need to add the following to your code:
cnetXML.ignoreWhite = true;
What can be done if any of your users have older versions of Flash Player in their browsers? These older players will not recognize the ignoreWhite function at all. One possible solution is to avoid the problem altogether and create a well-formed XML file that does not contain any white space.
This solution is obviously applicable if you are creating your own XML. But if you're using someone else's XML file, there's no way to guarantee that it doesn't contain white space. Fortunately, Colin Moock (the author of ActionScript for Flash MX: The Definitive Guide) had the bright idea of creating a routine that strips out white space from XML tags without relying on the ignoreWhite function. Another bonus: The code works in all Flash Player versions 5.0 and above. You can download his ActionScript for free.
In terms of performance, if you are generating your own XML, keep in mind that the Flash parser will handle attributes more quickly and efficiently than child nodes. The following is an example of XML code that has not been optimized for Flash:
<position>Chief Software Architect</position>
Here is the same example written as Flash-optimized XML:
<microsoft name="Bill Gates" position="Chief Software Architect">
Navigating the node tree
The Flash XML object has many functions and methods to access all elements of an XML tree once it has been loaded in. Flash can do recursive searches that are similar to the functionality found in Microsoft's XML DOM implementation.
To fully demonstrate the capabilities of Flash with XML, we will import into a Flash movie one of the Really Simple Syndication (RSS) XML feeds from News.com. The RSS is an XML format used to allow the free distribution of news headlines and descriptions to any Web site that wants to publish them. Moreover.com also uses the RSS format to distribute customized news feeds. Here is a link to the News.com RSS feed page.
Let's quickly analyze the News.com E-Business XML news feed and examine how we extract elements from the nodes using Flash. Listing A offers an excerpted portion of the XML file.
In the first frame in the ActionScript layer of our Flash movie, we load in our XML file. Once the file has been successfully loaded, the extractData function is invoked:
cnetXML = new XML();
cnetXML.ignoreWhite = true;
The easiest way to access the nodes in your XML file is by using the childNodes array. The rootHandler variable contains an array of all the elements at the topmost (or Root) level. The only element available is channel. Therefore, we must dig down to the next level. nodeHandler contains an array of child nodes belonging to the channel element. The first child node of the channel element is title, which contains "CNET News.com - E-Business". This value is assigned to a variable called source:
rootHandler=this.firstChild.childNodes; // First level - <channel>
nodeHandler=rootHandler.childNodes; // Second level
The next step involves looping through the array looking for nodes named item. These nodes contain the news titles, URLs, and descriptions. For each item node, we create an array of child nodes called childHandler. The first element of the array contains the title, then the link and description. Finally, the results are dumped into a dynamic text box called xmlfeed and displayed in the Flash movie, as shown in Listing B.
Be sure to try out the full working demo of this Flash movie. Other functions exist such as appendChild and removeNode. They will permit you to add and delete nodes from the XML tree, which is stored as an object in Flash.
Saving and updating XML files
Flash can't save XML files on its own. To back up the changes you made to any XML file, you must create a dynamic server-side application that will do the job. The sendAndLoad function will easily send the contents of an XML object to a PHP application. Here is an example:
From the dynamic server page (in the above example, savexml.php), the XML packet data can be retrieved by accessing the $HTTP_RAW_POST_DATA server variable.
Increase the functionality of your movies
As you can see, the combination of Flash and XML can prove to be extremely useful. This primer should give you some insight and information to help you bring XML data into your own Flash movies and applications.