Flash CS3: Loading an XML with AS3

Good lord, I just got a bit time to explore the new AS3 language, and my troubles already started. ;) No just joking,
Let’s get back to reality, it’s in deed quite different then with AS2 where you created an XML object and had to go through the all known firstchild, secondchild, bastard child, to finally be able to get your data, sure you could also install some classes from bit101 which gave you the ability to surf though an xml with XPath.
Though I think that the improvement Adobe did meeting the E4X regulations is much nicer.

First let us check our XML file, I’m using this XML file because I’m soon releasing a new version of my MP3 player completely made with AS3 so, this is how my XML looks like:

<playlist>
	<track>
		<title>TestTrack 1</title>
		<band>Band1</band>
		<file>test1.mp3</file>
	</track>
	<track>
		<title>TestTrack 2</title>
		<band>Band2</band>
		<file>test2.mp3</file>
	</track>
	<track>
		<title>TestTrack 3</title>
		<band>Band3</band>
		<file>test3.mp3</file>
	</track>
	<track>
		<title>TestTrack 4</title>
		<band>Band4</band>
		<file>test4.mp3</file>
	</track>
</playlist>

If you compare with AS2, nothing big has changed besides of me getting older and more experienced, in other words I’ve stopped using attributes for everything ;)

Next we are going to have a look at our actionscript which parses the XML.

Just open a new document and just for the matter of organization save it on the same location as your XML file, we should keep basics simple and not complicated.

On your newly created document, press F9 to bring up the actions panel, and as soon as you start typing Flash will show you the possible options you have for class you are loading in, I know that was already available on previous versions, but this time, it’s really helpful specially when you begin to learn a new language, by the way, I constantly try to keep the help panel open refering to the AS3 language reference.

With AS3 you using the new URLLoader class which somehow replaces the XML object from the early days, here we define a variable called xmlLoader which will be our XML container.

var xmlLoader:URLLoader = new URLLoader();

If you remember how you loaded XML with Flash 8 or lower, you for sure know the “noob” way of checking if it was loaded or not with the if.. statement, now we add Event Listeners to our containers and assign them an action to do when the event has been completed.
In our case we added an Event Listener to the xmlLoader container which tells us when the XML has been loaded and as soon that happens, the listener should call up the function named showXML.

xmlLoader.addEventListener(Event.COMPLETE, showXML);

this stayed ore or less the same like on AS2, below we’re loading the XML file into our xmlLoader container, keep in mind that URLRequests are ALWAYS string based

xmlLoader.load(new URLRequest("playlistAS3.xml"));

Basically our XML file has been loaded already, now we just want to display it very briefly to see if everything is running smoothly, for that we create a function called showXML.

function showXML(e:Event):void {

We ignore our white spaces, as before on AS2

XML.ignoreWhitespace = true;

We give our XML a variable called songs, I try to keep my variables and the XML as tight as possible so if my main child is called bugs, I would also call my variable bugs, got it? :)

var songs:XML = new XML(e.target.data);

If I would like to see how many items / nodes I have on my XML you just need to call the XML up and with the (.) syntax navigate through the XML till you reach your firstChild and check how many of those are around with the length() statement.

trace(songs.track.length());//Result is 4

I don’t think we need to explain this, anyhow, you create a variable called i and defined as a Number (numbers always start with 0)

var i:Number;

Do you remember for loops? No need to panic, they stayed the same :)
As a reminder: i equals 0, as long as i isn’t greater then the length of the xml, add one number to the variable i

for (i=0; i < songs.track.length(); i++) {

And lastly since you want to see that your code is really working let’s create a short trace block, displaying the contents of each node, declaring the title of the song as well the filename of the song.
To browser through the XML, you just need to point to your XML variable, remember it’s called songs, we add our little i to that variable so flash knows which instance it needs to be taken from, add the desired node name to it, in our case title and display with the text() statement.

trace(" Name of the song: "+ songs.track[i].title.text());
trace(" File Location of the song: "+ songs.track[i].file.text());
	}
}

Here the complete code for reviewing:

var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, showXML);
xmlLoader.load(new URLRequest("playlistAS3.xml"));
function showXML(e:Event):void {
XML.ignoreWhitespace = true; 
var songs:XML = new XML(e.target.data);
trace(songs.track.length());
var i:Number;
for (i=0; i < songs.track.length(); i++) {
trace(" Name of the song: "+ songs.track[i].title.text());
trace(" Name of the Band: "+ songs.track[i].band.text());
trace(" File Location of the song: "+ songs.track[i].file.text());
}
}

That was it, I hope you understand now the basics of the XML loading process with AS3, sure there is more to learn about it, and I definately advise to do so as well, keep an eye on the built-in flash help (which is by the way constantly updated).
It only lefts me wishing you a lot of fun working with AS3 and whenever you have a question, just drop me a note on my blog.

Tiago

Leave a comment

84 Comments.

  1. @Stephen – you can append the name of the text box at the beginning of each print so it will look like something like this content_txt.text = content_txt.text + “Name of Song:” + …. hope it helps.

  2. thanks a lot for sharing keep it up :smile:

  3. Hello,

    I’m trieng to load an xml the same way as you do. But problems appear when i try to run it on a webserver and when its inside a web page.

    Any tips for that?

  4. @Guido VS: is the path to the XML correct when on the webserver? That’s the common mistake when uploading to a webserver. Cheers

  5. Hey,

    Ye sorry i didnt got back to this page after solving the problem.

    The xml was in the same folder as the flash file. But i guess it uses the url from the page that does load the flash.

    So we had to add the entire path indeed.

    Took like 2 hours to find out. I was looking for a security problem :oops:

  6. I’m working with CS5/AS3, and your article rocks! Yours was the only one that worked out of 5 other tutorials. Please keep sharing! :grin:

  7. Hi.

    As we now there are some complication with accessing local resources using URLLoader, I propose some other way of reading XML:

    1. Declare XML file

    2. Read XML nodes for ex. this way:
    function ReadServicesPathsFromXML():void
    {
    mappings.ignoreWhite = true;
    for(var i:int=0; i < mappings.children().length(); i++)
    {
    var child:XML=mappings.children()[i];
    var xmlName:String=child.name().localName;
    switch(xmlName)
    {
    case "WebServiceWSDL":
    wsdlPath = child.text()[0];
    break;
    case "TiffHandler":
    tiffHandlerPath = child.text()[0];
    break;

    }
    }
    }

    3.
    My exemplary XML file look like this:

    http://170.22.4.129:81/service.asmx?WSDL
    http://170.22.4.129:81/TiffHandler.ashx?

  8. upps, sorry, problem with pasting:

    …nodeValue…
    …nodeValue…

  9. @Truth.. which problems did you bump into using the URLLoader? Security Sandboxes?

  10. Yes. But don’t use it for loading any application init values stored at XML file inside methods called at “creationComplete”. Object will be not avalible yet.

  11. very useful, thanks!

  12. great tutorial, worked perfectly but there’s one thing bothering me. I’m using an xml file in a flash file to populate a dynamic text box. But when I load text from this, it’s not using the formatting I’ve set for the text box. Is there anyway for it to use the formatting or do I have to declare the formatting in the xml file?

  13. Quick question. Now that I have my list of MP3′s loaded, I would like to reference that XML and play a voice over from that list.

    I’ve tried customizing an FLV – XML video list but I keep getting the wrong sound format error.

    myList.addEventListener(Event.CHANGE, itemChange);

    function itemChange(e:Event):void {
    channel = snd.play(myList.selectedItem.data);

    }

    ANy clues or suggestions would be great.

  14. You could have share the source file in compress format, anyways Thanks wink:

  15. Not sure what you mean by compress format.

    But I did find a solution.

  16. Thank you so much for this clear explanation!
    I’ve spent the entire afternoon trying to get my XML parsed, this finally did the trick.

  17. Thanks for this! It really helped a lot, saved a lot of time for me :D

    @Bernard
    I know this is 8 months late, but it’s better to use appendText than to set the .text property. It’s much, much faster :wink:

  18. Hi,

    Thanks so much for this. I’ve been struggling to get AS3 to read xml and this works a charm! :)

    I was wondering how I use the data outside the function. I tried creating an array and referencing that outside the function, but it doesn’t work. I tried the following:

    var imageArray:Array = new Array;

    var xmlLoader:URLLoader = new URLLoader();
    xmlLoader.addEventListener(Event.COMPLETE, showXML);
    xmlLoader.load(new URLRequest(“defaultCars.xml”));

    function showXML(e:Event):void{
    XML.ignoreWhitespace = true;
    var vehicles:XML = new XML(e.target.data);
    var i:Number;
    for (i=0; i < vehicles.car.length(); i++){
    imageArray[i] = vehicles.car[i].image.text();

    }
    }

    trace (imageArray[0]);

    I'm probably doing something wrong! :D

  19. hey guys.
    im trying to make a if statement so that one of three xml files can be played have you got any ideas?

  20. Fernando Freitas

    I’m sorry buddy but, is this some sort of tutorial?
    If so, you skipped too many steps and the way you explain things really suck!
    You might be so friendly and funny on the way you talk about how experienced you are but when it comes to teach something, you forget the fact that there maybe some people without any knowledge about flash dude! Perhaps you think people can read your mind or something! :idea:

    • wow, you commenting on a 4 year old blog post I made.. while I was one of the first posting about this topic.. If that is your thought then I’m happy you shared it with me.. I will think about what you said and maybe learn something about it. Nevertheless yes this blog is not for the complete noob and not for the professional user, it’s for the intermediate user. There are dozens and dozens of other sites aimed for beginners..

  21. I am trying to push the xml replies through an array into dynamic textboxes and having a hard time. Anyone have an easy solution? I see some of the same code here that I have been using but this tutorial traces to the output, not really attaching the pushed array information to dynamic text fields. Can someone point me in the right direction?

  22. What did you mean by in AS2 you had to do an “if” to know when XML was loaded? Were you *that* noob that you did not know about assigning a function to “onLoad” ??
    :shock:

  23. as;ldjas;dmaso;mdaso;

  24. I want to load XML File in Flash AS3 File in textField And When I Click on a button (next_btn), I will reach at next SongName

  25. I want to load XML File in Flash AS3 File in textField And When I Click on a button (next_btn), I will reach at next SongName :razz:

  26. How would this fla file to capture the XML of a page made ​​in wordpress, carrying an image and text in a rollover effect :?:

  27. The information on your website is good. looking forward for more postings.

  28. thanks man!

Leave a Reply

Your email address will not be published.


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Trackbacks and Pingbacks: