Sometimes you need to pass a flash file information. Perhaps you're making a flash-based photo gallery or an mp3 player. Maybe you want to use flash to parse server information. Whatever you need to do, it may make the most sense to use XML to pass your data to flash. Using XML is good because it's easy to parse as flash has built-in XML tools. In order to use an XML file, you need flash to do 2 things: read it and parse it. Here's an example of the code you'd need to read in an XML file (called info.xml) and parse it:
| data_xml = new XML();
data_xml.ignoreWhite = true; data_xml.onLoad = function(success) { if (success) { //point to the first node with information var track_xml = data_xml.firstChild.firstChild; //loop through each node while (track_xml != null) { //print out each node trace(track_xml.toString()); //point to the next node track_xml = track_xml.nextSibling; } } else { trace("error reading file"); } delete data_xml; }; //load the XML file data_xml.load("info.xml"); |
What the code does is load the XML file, then goes through printing out each node. It ignores the top level node so that you can contain your nodes to keep your XML up to spec. Since flash has built-in XML functions, it's a breeze to walk through each node and parse the data as you see fit.
But you want a specific example of what the code does, right? If 'info.xml' contained the following:
| <?xml version="1.0"?>
<flashsandbox> <game name="StarFall" URL="http://FlashSandbox.com/games/StarFall#file" /> <game name="Tower" URL="http://FlashSandbox.com/games/Towerv1#file" /> </flashsandbox> |
The code would print out:
| <game name="StarFall" URL="http://FlashSandbox.com/games/StarFall#file" />
<game name="Tower" URL="http://FlashSandbox.com/games/Towerv1#file" /> |
In order to use the code, you must understand how to extract the attributes from the nodes like 'name' and 'URL'. Given any XML data, flash allows you to access attributes directly like so:
| track_xml.attributes.name |
or
| track_xml.attributes.URL |
The attributes are case sensitive, so if you encounter an issue, check your spelling and capitalization. You can now create a custom XML file with the data you want to parse. Also remember that you can have flash load files from a webserver by including the entire path, 'http://' and all, in your .load like so:
| data_xml.load("http://www.mysite.com/info.xml"); |
Some uses for loading external data:
- If you know a scripting language you can have XML files that are created on the fly to allow users to customize your flash files
- Photo gallery or mp3 player
- Setting highscores or other game variables
- Parsing server information
There are lots of other uses for XML in flash, just use your imagination!


