http://xtutorials.net

Load content from XML files PDF Print E-mail
Written by Administrator   
Wednesday, 22 August 2007 19:28
In this tutorial you will learn how to load content from XML files. This is very useful if you plan to load content (such as text or some parameters) without modifying the SWF file. This way you can create an "engine" that loads everything.

OK! Let's get started. First of all let's create a new document in flash. A simple 300x100 will be just good for us. We won't put anything on the stage at this moment. We will focus only on the AS part.
In the first frame we have to declare that we are using an XML file.
Put this code:
_root.file = new XML();
This way we declare to flash that _root.file is an XML function.
To make sure all blank lines are ignored we have to ad the following line also:
_root.file.ignoreWhite = true

Now that we have loaded our XML function we have to tell it when to execute it. Usually we do that then the file loads, but it can be done anytime.
Here is how we do that.
_root.file.onLoad = function(){

}

This way when we load the file this function will be executed. Now...what we want to do? Load some data from the XML file.
to do that we ad the following lines of code:
_root.file.onLoad = function() {
no = this.firstChild.childNodes.length; //This will return the number of items the XML file has. We don't need it now but maybe you will need it later

//loads the items. in this example we have only two items
_root.content = this.firstChild.childNodes[0]
_root.txt= _root.content.attributes.txt;
_root.labelNo = _root.content.attributes.no;

}
Now that we have the function that loads everything we must initiate it.
_root.fileToLoad = "file.xml"; //The file that we want to load.
_root.file.load(_root.fileToLoad);

Now let's put to text objects on the stage to see if everything is loaded corectly.
Make them dynamic text. One has the var name _root.txt and the other one _root.labelNo
Before we test the SWF file we have to create the XML file.
Create a new file with notepad and name it file.xml. Save it in the same directory as the FLA files.
now make it like this:

<content>
<content txt="text for this" no="45" />
</content>

Now test the movie. You should see that the content from the XML file was loaded and the text fields show it.
Also remember that if you have more items that folow the same structure you can put a "for(i=0; i,no; i++)"

You can download the fla file from here: Flash_XML_Tutorial.rar
Last Updated ( Wednesday, 22 August 2007 19:31 )