This tutorial will demonstrate how to upload, download and work with XML in Actionscript 3. First off let's make a sample XML file.
<?xml version="1.0" ?>
<FAMILY surname= "Smith" location= "New York">
     <SON name="Dave"  bday= "08/10" /> 
     <SON name="Bob"  bday= "05/06" />
     <DAUGHTER married_name="Perone">
         <GRANDCHILD age="5" />
         <GRANDCHILD age="6" />
     </DAUGHTER>
</FAMILY>
Downloading XML from a server is pretty much like any other thing.
loader = new URLLoader(new URLRequest("http://www.example.com/family.xml"));
loader.addEventListener(Event.COMPLETE, xmlDownloaded);
Once we've downloaded the XML though, Actionscript 3 has a bunch of convenient things built right into the language to access the XML elements in various ways.
function xmlDownloaded(event:Event):void {
    var xmlData:XML = new XML(event.target.data);

    var surname:String= xmlData.@surname;
    var location:String= xmlData.@location;

    //  get the first granddaughter's age of the first daughter
    var grandchild_age:Number= Number(xmlData.DAUGHTER.GRANDCHILD.@age); 

    // search through all elements inside FAMILY
    for each (var object:XML in levelData.*) {
        if (object.name() == "SON") {
            var bday:String= object.@bday;
        } else
        if (object.name() == "GRANDCHILD") {
            var age:Number= object.@age; // will automatically convert to Number
        } else
        if (object.name() == "DAUGHTER") {
            var num_grandchildren:uint= object.*.length();
        }
    }
    
    // search through all child nodes of DAUGHTER
    for each (var:grandchildren:XML in levelData.DAUGHTER.*) {
        var ageStr:String= grandchildren.@age;
    }
}
Accessing properties of an element is as easy as using the '.@' operator and accessing children is just simply typing .whateverchildname (you can also get any XML elements's name and attributes with the .name() and .attribute() functions). To access all elements at some point in the tree you simply use the '*' wildcard operator.
One important thing to notice above is the xmlData.DAUGHTER.GRANDCHILD.@age. There are multiple GRANDCHILD's and potentially multiple DAUGHTERS (if we so choose to add more). What does it mean to get the age attribute then?
What's going on here is that you can simplify indexing into the first child element of a node by omiting the [0]. This was done to simplify cases where a node only has 1 child.
One final important function is the .parent() which gets the parent node of the element.
Let's take a look at how to change the XML data and upload it back to the server.
function uploadXML():void {
     var family:XMLList= new XMLList();
 
    // add a son named Will to the end of FAMILY
    family += <SON name="Will" bday="01/15" /> 
 
    family += <DAUGHTER married_name="Potter" />
  
    var grandchildren:XMLList = new XMLList();
    grandchildren += <GRANDCHILD age="1" />
    // associate the grandchildren with the last child
    family[family.length()-1].setChildren(grandchildren);
 
 
    // upload the XML to a php script
    var loader:UrlLoader = new URLLoader();
    var request:URLRequest= new URLRequest("http://www.example.com/uploadscript.php");
    request.contentType = "text/xml";
    request.data = family.toXMLString(); // convert to a string
    request.method = URLRequestMethod.POST;     
    loader.load(request); 
}
Pretty easy huh? All you have to do is a += to add new XML nodes. You can also deliberately set the children to a collection of nodes (XMLList) by calling setChildren and there is even insertChildAfter and insertChildBefore (not demonstrated here).
The easiest way I've found to upload the XML data to the server is to set the content type as text/xml and just upload it as the data rather than setting up a URLVariable to be equal to the text.
<?php
$fh = fopen("family.xml", 'w') or die("can't open file");
fwrite($fh, $HTTP_RAW_POST_DATA);
fclose($fh);
?>
One last caveat is when we upload in the aforementioned fashion, the PHP script needs to read from the $HTTP_RAW_POST_DATA variable instead of one of the $_POST or $_GET variables. This example takes the posted XML data and writes family.xml from with it.

That's pretty much most of what you will work with when using XML in Actionscript 3 although there are more methods to work with. You can find the XML documentation on the Adobe Flex 2 Language Reference. A complete reference for using XML in Actionscript 3 can also be found at the ECMA 357 Standard (E4X).
50 Comments
Justin
What if there were more than one family tag to get information on multiple families?
Will
To use the XML type, there must be one meta container wrapping everything. If there were multiple families you could either use XMLList instead or wrap the families in a meta family tag like &lt;POPULATION&gt; or something
System admin
Yeah, kinda but not really. Shoulda, woulda, Coulda but not going to happen.
Jean
Thanks a lot! But when I tried it all (copy > paste), the upload php replaces all the previous text in family.xml by the new additional Son "Will" en Daughter etc.. What 's wrong?
Will
The fopen("family.xml", 'w') in the PHP code is set to overwrite mode; to append onto the file instead, use 'a' instead of 'w'.
Hyzszddw
great work dude thx
Ggxlyssg
This site is crazy :)
Vealpvyy
good site dude
Ikzectcb
this is be cool 8)
Liviu
Thanks, your example is the only one I could find where they didn't send data as URLVariables. And I had trouble accessing the sent text data from php, that was because I hadn't set the contentType property, which is VERY important. Without it, php does not fill the $HTTP_RAW_POST_DATA var. This property is not emphasized on any of the examples I've seen, and they all use URLVariables(which doesn't require contentType to be set, and so it hides this problem). I just hate those strictly-URLVariables-example-creator guys!
Will
URLVariables are definitely not the end all be all of sending parameters from Flash. You can even do something as simple as new URLRequest("example.com/whatever.php?var1=value&var2=value");
I have done combinations of that AND URLVariables before for various reasons.
Daniel Avco
Thanks,saved me a lot of time. The $HTTP_RAW_POST_DATA is key to getting this method to work.
Alex Feliciano
how about sending the XML with ASP in .NET
alex Feliciano
http://www.kirupa.com/forum/showthread.php?t=261587
Will
It should work the same way no matter what backend you have on the server.
Will
The important thing to note here is to make sure you are setting the contentType as mentioned by Liviu and that article on kirupa. I believe AS3 may do this automatically but other languages like ASP, Javascript,PHP may not. This is why when you do an AJAX call and you request XML you have to set the contentType in the js and PHP as well. To set the content type in PHP do:
<pre>
header("Content-Type: application/xml; charset=ISO-8859-1");
</pre>
You can use whatever charset is appropriate.
Andcljoh
Wonderfull great site
Vbschfwg
Jonny was here <a href=" http://www.jamendo.com/en/user/Redtube ">free porn videos redtube</a> 653
Dmjexlui
Jonny was here <a href=" http://www.jamendo.com/en/user/89Movies ">89galleries</a> 301403
Fa
Hi, I tried it, but it says it doesnt recongnise levelData. Ive never heard of it. What is 'levelData'? Also, you forgot to declare loader. Also, you have some sintax errors in your script (e.g. var grandchildren:XML).I think its pretty sad that you pasted this thing here without compiling it first. Thanx, but please, next time check your errors before pasting this.
Mi
Can't get it to work. the download as3 has lots of errors. The upload is fine but doesn't do a thing to my php script. is there some missing script in the php file?
Wouter
Great tutorial but I think I did something wrong.. my new xml node is placed AFTER the </FAMILY> tag, but I don't know what I did wrong?
vadya
uBc4Fe this http://www.google.com is google
Greg
There were some typos in the example.... Please check this version....
var loader:URLLoader = new URLLoader(new URLRequest("family.xml"));
loader.addEventListener(Event.COMPLETE, xmlDownloaded);

function xmlDownloaded(event:Event):void {
var xmlData:XML = new XML(event.target.data);

var surname:String= xmlData.@surname;
var location:String= xmlData.@location;

// get the first granddaughter's age of the first daughter
var grandchild_age:Number= Number(xmlData.DAUGHTER.GRANDCHILD.@age);

// search through all elements inside FAMILY
for each (var object:XML in xmlData.*) {
if (object.name() == "SON") {
var bday:String= object.@bday;
trace (bday);
} else
if (object.name() == "GRANDCHILD") {
var age:Number= object.@age; // will automatically convert to Number
} else
if (object.name() == "DAUGHTER") {
var num_grandchildren:uint= object.*.length();
trace (num_grandchildren);
}
}

// search through all child nodes of DAUGHTER
for each (var grandchildren:XML in xmlData.DAUGHTER.*) {
var ageStr:String= grandchildren.@age;
}
}
Kent
Thanks, this is exactly what I needed! The only thing was flash didn't recognize 'UrlLoader' until I changed the capitalization. Thanks again so much!!!
rohit
good way to start with accesing xml in as3
molly
gj9X2o viTwQ937Baww5mLp1oWxu
JOCGWZbSVohBF
270_118.txt;8;12
sushant
Great and very good
Toks
Good. In the case of age, it automatically converts to number.
But, assume you have an arithmetic expression as a node content. how do you evaluate and return result instead of a string (b'cos: trace(node.exp) will return a string not the result of evaluation - see xml below)
<node>
<exp>10 + 5 * 20</exp>
<node>
Toks
For above, assume the xml is: <node><exp>10+5*20</exp><node>
Toks
My text not showing the xml script example? why? Note, 10+5*20 should be a node content.
Will
Sorry about the xml not showing up, there was a bug in the php code. AS2 and Javascript both have an 'eval' function you could call to actually solve that but as far as I know AS3 does not have that. There is a library called AS3Eval (http://eval.hurlant.com/) that you can try out but I've never tried it.
Toks
Will

Thanks for the library. Its not actually for the stated type of problem. But, I'm still on a way out for a solution.


Toks
sara
please show abemo for this examble
kwame
Nice Tutorial Thank you.
But: say I want to allow users to view a list of images from database and to upload their images to db. I'm using Flex,grails and mysql. Any idea will be welcome.
Thank you,
kwame.
xdeath
what i'd like to know is how as3 knows were to add the data to. when its added he says it will go to end of family and when he adds grandchildren into the daughter catagory, but how?

he says it will do this but how it goes there is anyones guess.
mongo
Great that you tried - and really helpful in some ways, but I never saw so many syntax errors in a single piece of code. Also, you seemed to have changed your mind about variable names a couple of times - which just leads to confusion.
Thanks for the effort - but would be great if you checked the code before posting.
mongo
Just looked at your bio - seems like you've been through a lot of really tough experiences - so good on ya that you're still in there trying!
AX
WALA NMAN
get pointer
hai men, i will save my xml, like this scenario:
i have a xml :
<xm>
<user>Andy</user>
<pass>123</pass>
</xml>

how to i add new data in this xml?
tq..
henry
hello, pls, i can only see how to convert an xml file to an actionscript flash. how about the other way round? i want to convert my actionscript fle back to xml. any idea, send to kanohen@gmail.com. thanks.
kashi
yep same question what henry asked
Your Name
kashi.com@gmail.com
Will
you can't convert a Flash file to an xml file.... do you mean load an external xml file into flash? Use URLLoader to load the file at runtime or you can embed the file at compile time. In FlashDevelop you will need to use the Embed tag, in CS3/4/5 you will need to add the asset to your library and create a symbol for it.
henry
Hello Will, please, i have an xml in a file and i want to work with the xml.. in the example you gave, you loaded it from the URL how about if the xml is in some local file.. can you modify that part of the code to reflect such problem? I also found out you can convert an xml to actionscript using the <mx:model> tag..u got any idea?
henry
I am sure i speak for everyone if i request that you attach a file containing a working code of this illustration. that way, people can test the code and understand better what you are trying to convey.
sdas
asd
Aditya
Hey Will!

I corrected the syntax errors and uploaded the xml and php files to my server and ran the fla file on my system. All seems to be working fine but there is no change happening to the xml file at all.
Please help! I need such a code for an important project I'm working on...

Aditya
Will
Sounds like it's an issue with your PHP that's writing the file. Make sure you are in the correct directory there. Have your script echo getcwd() to see what dir it's trying to write to. Also make sure your file has the correct permissions set, www-root should have write permissions to that file.