AS3 Basics: Loading & reading XML tutorial

One of the biggest improvements AS3 has over AS2 is the way xml is now handled. The old node syntax has been replaced with the more intuitive ECMAScript (E4X). This short tutorial introduces you to key concepts of working with xml in AS3.

Step 1: Create the xml file.
<?xml version="1.0" encoding="utf-8"?>
<data>
	<news date="07-04-2009">
		<title>
			Here is title of our message.
		</title>	
		<message>
			Here is our message. 
		</message>	
	</news>
	<news date="06-04-2009">
		<title>
			Here is another title of our message.
		</title>	
		<message>
			Here is our another message. 
		</message>	
	</news>
</data>

Copy the code into a text editor (we recommend notepad plus) and save as news.xml.

At the top of the xml file we have the header which contains the xml version and encoding information, under the header we have our data element (the root element). Inside we have the news elements, each one containing an attribute called date and two elements called title and message. If you have ever worked with xml before, none of this will be news to you.

Step 2: Loading the xml

Create a new fla named xmlLoader.fla and a new class named xmlLoad.as with the code below. Link the two files by using the document class in xmlLoader.fla. This is found in Properties > Publish, type “xmlLoad” in the class field.

package {
        
    // import needed classes  
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.display.Sprite;

    // we extend sprite instead of movieclip as no timeline is needed    
	public class xmlLoad extends Sprite {
 
        // our xml object
		private var xml:XML;  
 
		public function xmlLoad(){
			readXML();
		}
      
		private function readXML():void {
           // load the xml file using the URLLoader class
			var loader:URLLoader = new URLLoader(new URLRequest("news.xml"))
           // call our xmlLoaded function once the xml has loaded 
			loader.addEventListener(Event.COMPLETE, xmlLoaded);
		}

		private function xmlLoaded(e:Event):void {
           // assign loaded xml structure to our xml object
			xml = new XML(e.target.data);
            xml.ignoreWhitespace=true;

        }
       }
}

To read a xml file in actionscript 3 we need a URLLoader, URLRequest, XML object and a event listener that will listen for the complete event.

We will focus on two function’s, readXML and xmlLoaded. In the first function we create the loader variable which is assigned to URLLoader which we pass the name of our xml file (in this case it`s news.xml), then we assign the Complete event listener with the xmlLoaded function as a second parameter. So when the loading of xml is completed the xmlLoaded function will be called. In the xmlLoaded function the data from the loader (e.target.data) is assigned to our xml object. After this assignment we can break the xml data down further.

Step 3: Extracting data

Here are some examples showing how to read elements and attributes from our xml file. These go inside the xmlLoaded function (line 30).

trace(xml.news[0].title);
// output = Here is title of our message.

Returns the first title element by simply using the names of the elements xml.news.title (our xml object is now the root element) The number [0], defines which news element we want to target.

trace(xml.news[1].@date);</p>
// output = 06-04-2009

Returns the second date attribute using the @ symbol followed by the name of the attribute

var i:Number;
for (i=0; i < xml.news.length(); i++) {
  trace(xml.news[i].message);
}
/* output = Here is our message.
            Here is our another message */

Loops through all nodes using a for loop and returns each message element.

Conclusion

Elements are targeted using the same names and hierarchy as in the xml file. If you want to read an element use ‘.’ plus the name, if you want to read an attribute of an element use ‘.@’ plus the name.

Download source files

The discussion so far...
Sammy
2 years, 6 months ago

Great tut, thanks for including the files.

Quote

kym
2 years, 5 months ago

you have a couple of typos in the code posted;
19: xmlLoad() should be readXML()

step 3 code 3

2: news

Quote

Gareth
2 years, 5 months ago

kym said: you have a couple of typos in the code posted;
19: xmlLoad() should be readXML()
step 3 code 3
2: news

Sorry! those are now fixed.

Quote

Jac
2 years, 5 months ago

Hello Gareth,

I’m beginner in Flash, I tried open your source file and found that “xmlLoader.fla is in unexpected file format” I’m using Flash CS3 Pro V9.

Jaganmohan Krishnamoorthy

Quote

Gareth
2 years, 5 months ago

Hi Jac,

Sorry! I had it saved for Flash CS4, try now as I have saved it in the CS3 file format.

thanks,
Gareth

Quote

Jason
2 years, 3 months ago

hi everyone,

can this code be used to upload text onto a blog am trying to attact a blog onto a web page and have not got a clue

cheers jason

Quote

netan
2 years, 1 month ago

Can you please tell me how you have embaded the xml on this page and which WP plugin or editor are you using to show the formatted colored xml snippet with line number.

Thanks in advanced.

Quote

Neisoneemarse
2 years, 1 month ago

Awesome .. really stunning matter. I will blog about it as well!

Quote

Magic
1 year, 11 months ago

Hej,
I cant get it to work, can you please help me?
when I play the swf file from you tut, I dont see anything…?
Im new to as3

thank you in advance.

nm

Quote

Nilay
1 year, 5 months ago

Very nice example!
Helped me very much.

Thanks!

Quote

Resources for Assignment 3 » Thomas Borzecki - Ramblings of a web mercenary.
1 year, 2 months ago

[...] Flash Blog: Loading & Reading XML – Another example, this time class-based, of how to load and process XML files. Posted in AVIS 325 Cancel Reply [...]

Lara Waller
1 year, 1 month ago

Thanks for the awesome tutorial mate, it’s just what i was looking for.

Quote

Magento Features
1 year, 1 month ago

Nice post.Thanks for sharing this.

Quote

Izetta Cotelesse
1 year, 1 month ago

Hey very nice blog!! Man .. Beautiful .. Amazing .. I will bookmark your blog and take the feeds also…

Quote

משחקים ברשת
1 year, 1 month ago

Great posting, thank you!

Quote

Pennie Rodino
6 months ago

Have you ever thought of adding some videos to your posts to keep the readers entertained? I just read through the post and it was quite good…thanks for the share

Quote

Carolann Scavone
5 months, 3 weeks ago

62. As I web site possessor I believe the content material here is rattling fantastic , appreciate it for your hard work. You should keep it up forever! Good Luck.

Quote

black ops download free
5 months ago

Excellent read, I just passed this onto a colleague who was doing some research on that. And he just bought me lunch as I found it for him smile Thus let me rephrase that: Thanks for lunch!

Quote

Episodes of Bad Girls Club 7
5 months ago

hello!,I really like your writing so so much! proportion we keep in touch extra about your article on AOL? I require an expert in this space to resolve my problem. May be that is you! Having a look ahead to peer you.

Quote

Codi Spinn
5 months ago

You have made several reputable items presently there. I seemed on the net for the issue and located most people should go along with together with your internet site.

Quote

naresh kumar
3 months, 3 weeks ago

thank you……….

Quote

natural food
1 month, 3 weeks ago

Thanks , I’ve just been looking for info about this topic for a long time and yours is the greatest I have found out so far. However, what in regards to the conclusion? Are you positive in regards to the source?|What i don’t realize is actually how you’re no longer really a lot more well-preferred than you may be now. You are very intelligent.

Quote

Soumya Vinod
2 weeks, 4 days ago

Found another relatively simpler way to do the same,posted at http://bbso.wordpress.com/2012/01/16/loading-xml-in-flash-as3

Quote



Leave a Reply

SEO Powered by Platinum SEO from Techblissonline