This article will show you basic connection between flash and XML, it will show you what to add in the flash file in order to be able to read tags from an XML file and then use that data inside flash.
Few details about the XML file
The XML that we will use will look like this, you can create a file called sample.xml and paste this in it:
In the above XML file the "products" are called XML tags and "product_name" and "price" are called attributes.
"Products" is the first child of the XML file and the lines inside are child 0,1,2 of the first child.
To get the value "Flash Book" you have to write this in ActionScript: my_xml.firstChild.childNodes[0].attributes.product_name
To get the value "Flash CD" use this code in ActionScript: my_xml.firstChild.childNodes[1].attributes.product_name
The flash file preview
Contents of the flash file
In our samples we created 6 text fields where the data (product names and product prices) is written but is not important how you use the data, in this article we want to explain how to read the XML data.
Now the contents in the flash file.... open Macromedia Flash, create a blank file, click on first key frame, open Actions panel and paste this code:
// define an XML object called "my_xml"
my_xml = newXML();
// load data from an external XML file into "my_xml" object
my_xml.load("sample.xml");
// what to do when data is loaded ... Call a function ("my_function" in this case)
my_xml.onLoad = my_function;
// ignore "white spaces", text nodes that only contain white space are discarded
my_xml.ignoreWhite = 1;
// function contents
function my_function(){
// take the data from the XML lines (line 0,1,2) and place that data inside text fields
As you may see, the above code loads data from an external XML file called "sample.xml" and places the data from the XML tags to text fields inside the flash file.
For example: to access the product name on first line ("Flash Book") the ActionScript line inside the flash file will be like this:
"my_xml" is the name given to the new XML object at beginning of ActionScript code; the next code are the levels, it reads from first level ("firstChild") this is "products" tag, from "products" tags it loads first child ("childNodes[0]") and the attribute name is "product_name".
So the above line will return the value "Flash Book".
As you can see counting starts from zero when counting XML lines.
Product_name, price and XML tags are defined by user, in an XML file you can name the tags and the attributes as you wish, the tags are not predefined like in HTML language.
Download samples
Rate this content; the results will appear next to article links in site: