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



August 9th, 2007 - 02:21
Thanks – this is helpful! I have a question though. I wanted to use this for my own band, so the tags are pointless, since there is only 1 option. I deleted them from the xml file thinking it wouldn’t make a difference but got an error #1090 (XML parser failure). When I put the tags back in, it worked fine. I don’t get it, the band data isn’t even referenced in your actionscript code. I must be missing something, can you explain?
August 9th, 2007 - 09:28
Aaron: Have you removed it from all the nodes?
I will have a look at it when I’m back home from work.
September 13th, 2007 - 01:34
aaron, your getting an error simply because you copied the XML file that Tiago gave, but he made a syntax mistake in the xml declaration.
He wrote:
it should be:
No space before the first ?
That should solve your error.
September 13th, 2007 - 11:13
Hi Didier
Thanks for pointing that out to me, I’ve checked my code and it looks like it’s currently an issue with my code displaying system, when I’m on edit mode I don’t see that whitespace. I’ll try to fix this issue asap.
Thanks for your comment and help
Tiago
October 18th, 2007 - 10:37
In you complete code you have this line:
race(” Name of the song: “+ songs.track[i].title.text());
Should be ‘trace’.
October 18th, 2007 - 10:51
Thanks for that Ferdi
*fixed
November 25th, 2007 - 14:19
Hallo, I am Czech and I have code to load xml file, but I have problem with encoding, Fash does not write czech letters corectly. I think that the problem is in encoding.
Will you help me, how can I solve it?
Martin
January 6th, 2008 - 17:28
Hi Tiago,
In the complete code, I think you mean to trace the band also.
I think you made a little copy-paste error.
corrected code snippet:
trace(” Name of the song: “+ songs.track[i].title.text());
trace(” The band of the song: “+ songs.track[i].band.text());
trace(” File Location of the song: “+ songs.track[i].file.text());
January 6th, 2008 - 22:23
you right
thanks for that Cor
Fixing that right now
May 5th, 2008 - 08:22
Thanks, this was exteemly helpful. I do have one question. I’m getting the xml file to load and the data in the file to display in flash on the web page. However, if I change the data in the XML file and then refresh the page, it still has the old data displaying in flash on the page. How do I get the action script to reload the new data in the xml file when the browser refresh is pressed?
Thanks much,
JR
May 6th, 2008 - 17:14
JR, try clearing your browser cache.
May 6th, 2008 - 17:33
I understand that and, yes, it will work just like ending the browser session and restarting it. However, the default setting for IE (I don’t know about other browser defaults) is to check for new pages Authomatically. When you hit refresh it does go out and update new images / text / etc. However, hitting refresh, the flash object does not seem to read from an updated XML file. THis seems strange that everything else will be refreshed from the server (when the refresh button is pressed) except the flash object.
May 10th, 2008 - 03:38
Thanks for the script its outputting with a semi organized way.
How would i get this to print to a dynamic text box?
May 13th, 2008 - 20:31
This was very helpful. Do you know how to go about moving through the XML file? Say you set up buttons via addChild() according to the number of records in the XML file, click to switch records? I can’t seem to find a tutorial on doing something like that. Thanks.
May 14th, 2008 - 00:17
JimR
the flash player / browser caches all XML’s so you need to add a random number assigned to a bogus variable to trick out the browser
yo joe
replace the trace with the name of your textbox:
AD
I’m so sorry, I didn’t understood your question, you mean you want to create some kind of navigation of your records on the XML?
May 15th, 2008 - 13:30
if you are having issues with xml being cached by the flash app just change your call to the xml file by appending a random variable to the end of the call as Tiago mentioned…
e.g.
// original call
xmlLoader.load(“myxmlFile.xml”);
// instead use
xmlLoader.load(“myxmlFile.xml?num” + (Math.random() * 999));
this will force the loader to load the file again as it assumes that the call has changed…
May 15th, 2008 - 13:31
oops…
// instead use
xmlLoader.load(”myxmlFile.xml?num=” + (Math.random() * 999));
May 21st, 2008 - 18:28
Is it possible too make flash update the information in the XML every xx seconds.
Since it is for a radio stream, and the XML holds the now playing data and stuff
Thx, Kontsnor
June 6th, 2008 - 20:20
Perfect, all I need know is a tutorial to put the XML data on the flash document. I want to do a full flash site with XML text and images. Thanks a lot!
June 17th, 2008 - 08:33
I love you!
June 20th, 2008 - 07:06
its really helpfull, i just wanna ask that is it possible that, i want to load images or videos into flash but the number of images or videos may varry each time. plz help me out!
June 23rd, 2008 - 18:22
How would you connecr that to a datagrid without driving the flash player crazy shooting these new dumbest error messages that developers only should see.
June 24th, 2008 - 12:59
You can find a running example and source file here
http://flashactionscriptandanimation.blogspot.com/2008/06/blog-post.html
Anil
anilkumarnd@gmail.com
June 30th, 2008 - 04:37
thank you
August 14th, 2008 - 15:38
@ncomp
thanx a lot! I’m using js to load xml and edit it with php, but I would only see the cached version in my browser.This costed me a lot of time trying to find an optimal solution to that problem, and your solution worked out perfect!
August 17th, 2008 - 15:45
hi,
i’m trying to load a xml file using a flash varibale in as3, here is my code
1.var urlRequest:URLRequest;
2.var urlLoader:URLLoader;
3.var rss:String = ‘http://xml.weather.yahoo.com/forecastrss?p=MOXX0001&u=c’;
4.var data:XML;
5.xmlLoader(rss);
and this is working well, just i want to change the var a rss in line 3 by using varibale with html code
is there some help please
10x
September 1st, 2008 - 14:33
Thank you so much for this tutorial! It has helped me a great deal in understanding how XML is handled by Flash. Keep up the good work
September 26th, 2008 - 20:28
Outstanding tutorial. I have my test page working.
I have a few questions.
1. My XML file has 10 separate songs and I simple want to display them in my flash file. Kind of like a simple catalog.
My functional test displays the 1st record and all 5 related text fields for that 1st record. However, depending on the physical size of my dynamic flash text box, the 2nd record or if there’s physical room the 3rd record data is displaying right behind the 1st. How do I only display the 1st record information? My loop seems to be grabbing everything all at once. Not just the 1st record.
2. How do I add navigation to this display? I’d like to be able to see the 1st record, then navigate to the Next, Previous, Last record with Flash. I’d like to just add some buttons or a graphic to click to request new information.
Once again outstanding tutorial, and thank you very much for sharing your time and information.
October 6th, 2008 - 00:19
Does anyone has a source file?
November 3rd, 2008 - 02:36
thanks for this. just what i was looking for.
November 25th, 2008 - 05:35
I am a new user to using xml to create a dynamic flash page. I found this tutorial really helpful in my studies. The only problem is; and I did try replacing the trace with the name of my text box; my text box only shows the last xml data. I created my own xml file and the trace works fine and will show me all four lines in the output window, but on the textbox I am only shown the 4th line. Instead of displaying listing 1, listing 2…etc each on it’s own line, the text box only shows listing 4. Any idea as to how I can fix this? My for statement appears to be setup correctly since the output window shows all of the traces. I am confused. Any help would be appreciated.
January 16th, 2009 - 12:21
Hi, very nice and though tutorial, I just want to have a scrolling xml textbox, can u give any link where i could find it..
thanks in advance
January 16th, 2009 - 12:22
Hi, very nice and through tutorial, I just want to have a scrolling xml textbox, can u give any link where i could find it..
thanks in advance
April 1st, 2009 - 12:06
dd@Jarryd
April 1st, 2009 - 14:54
hey
will someone help me with displaying an image in flash using as2.0 from XML doc., ihave parsed the image but displaying is the problem.i m a beginner so dont know too much in deep.Any help is appriciated
April 2nd, 2009 - 12:16
dfasdff
May 7th, 2009 - 22:58
Goooood jobs guys
May 13th, 2009 - 00:09
@adil
I’m trying to do the same thing. Can anyone help?
June 18th, 2009 - 02:35
Thanks for this quick tutorial, it’s exactly what I needed for a project.
June 18th, 2009 - 08:42
Great tutorial. I was searching for this info for hours. Want to make a little application that fills several components with XML, and this helped a ton in understanding how to use XML in AS3 (I was pretty familiar with it in AS2).
Thanks!
August 10th, 2009 - 10:34
Hi
iam very much new to xml
iam making a xml file in which i want the user name to change dynamically
can any1 take me out of this
thanx in advance
August 13th, 2009 - 08:15
do i need to do any imports??
i have this error..
Error #2044: Unhandled ioError:. text=Error #2032: Stream Error. URL: file:///C|/Users/juan/Desktop/video/galeria.xml
at myVideoInvicta4_fla::MainTimeline/myVideoInvicta4_fla::frame1()
September 1st, 2009 - 13:22
this is great`-`
works great, but I would like to ask how to create a next button/previuos button for this?
suppose I have some text fields that loads the first node by default (easy), then if I press a next button I will load the text of the next (second node)? I am stumped by the AS 3not the design I hope you can offer help.
Thanks,
Mike
September 6th, 2009 - 15:34
Thanks for the nicely explained tutorial. Any advice on how I could get flash to load xml or node for current date? I know how to get current date with flash and on the verge of figuring something out, but was hoping for some help to speed things up a bit.
September 25th, 2009 - 15:41
@Juan
Check that the names of the files in the xml are exactly the same to the names of the actual files. This error has happened a lot to me and it’s just a misspelling error.
November 8th, 2009 - 12:42
hey did u find a solution for this problem, i want to do exactly the same thing??
November 16th, 2009 - 18:53
@Kontsnor
hey did u find a solution for this problem, i want to do exactly the same thing??
November 18th, 2009 - 18:52
thx very muchhhhhhhhhhh
December 15th, 2009 - 23:37
What about E4X? I used E4X when coded in as3 my smooth xml picture gallery
–comment edited by admin: no product advertisement –