Let’s begin by creating an XML document. Here the information I’ll need for a game I’m building:
-
Chord name
-
Keys that make up the chord
The XML information will appear as follows:
<muse>
<chord label="C chord">
<key data="c.mp3"></key>
</chord>
<chord label="D chord">
<key data="d.mp3"></key>
</chord>
</muse>
You can use any text editor to create this document, including Microsoft’s Notepad and the Mac OS X’s TextEdit. The next thing we do is open Flash to do the Actionscripting to read the XML document we created. The first part of the ActionScript involves declaring an XML object:
var xml:XML = new XML();
We now have an empty XML container object in which we will place our XML data. The next step involves creating a loader to load our XML data from an XML document somewhere in our folder. I’m assuming you created the XML document in the same folder you have saved your Flash file.
var xmlLoader:URLLoader = new URLLoader();
We’ve now just created an empty loader object that we will use in just a minute. Now we begin the request to call up our XML document which I’ve called “chords.xml”.
xmlLoader.load(new URLRequest("chords.xml"));
Before we can use any of the data inside the XML document, we must wait till it has loaded completely. So we’ll add an event listener to our loader.
xmlLoader.addEventListener(Event.COMPLETE, loadCompleteHandler);
After that we’ll need to write up our function loadCompleteHandler which will be called when the event COMPLETE gets dispatched.
function loadCompleteHandler (evt:Event):void
{
xml = XML(evt.target.data);
}
Once it is called, this function will take the data from chords.xml and create an XML object out of it and store the resulting data in our variable xml. If you compile your Flash file, you won’t see anything on the screen. Let’s add a dynamic textfield. Make sure that you set the selectable property off. Give this textfield an instance name: title. Now we’ll add a few more lines of code to our previous function loadCompleteHandler.
function loadCompleteHandler (evt:Event):void
{
xml = XML(evt.target.data);
title.text = xml.chord[0].@label;
}
The last line inside of the function accesses the top-most chord child of the XML document and reads off the attribute called “label”. Compile the Flash file and you should get the following output.
