Will Perone

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);

    // get children by variable if you don't know the element name upfront and set an attribute 
    var childvar:String= 'SON';
    family.elements(childvar).@surname= 'Perone';
 
    // 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).
81 Comments
Justin 217 237
What if there were more than one family tag to get information on multiple families?
Will 38 31
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 77 76
Yeah, kinda but not really. Shoulda, woulda, Coulda but not going to happen.
Jean 16 16
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 20 21
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 32 33
great work dude thx
Ggxlyssg 21 21
This site is crazy :)
Vealpvyy 22 367
good site dude
Ikzectcb 5 447
this is be cool 8)
Liviu 9 9
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 23 25
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 12 12
Thanks,saved me a lot of time. The $HTTP_RAW_POST_DATA is key to getting this method to work.
Alex Feliciano 5 5
how about sending the XML with ASP in .NET
alex Feliciano 10 10
http://www.kirupa.com/forum/showthread.php?t=261587
Will 7 6
It should work the same way no matter what backend you have on the server.
Will 28 26
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 23 19
Wonderfull great site
Vbschfwg 0 13
Jonny was here <a href=" http://www.jamendo.com/en/user/Redtube ">free porn videos redtube</a> 653
Dmjexlui 26 26
Jonny was here <a href=" http://www.jamendo.com/en/user/89Movies ">89galleries</a> 301403
Fa 59 58
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 21 21
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 3 12
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 1 10
uBc4Fe this http://www.google.com is google
Greg 1 7
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 85 15
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 0 7
good way to start with accesing xml in as3
molly 0 2
gj9X2o viTwQ937Baww5mLp1oWxu
JOCGWZbSVohBF 1 7
270_118.txt;8;12
sushant 0 6
Great and very good
Toks 0 4
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 2 6
For above, assume the xml is: <node><exp>10+5*20</exp><node>
Toks 0 8
My text not showing the xml script example? why? Note, 10+5*20 should be a node content.
Will 1 8
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 0 6
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 0 3
please show abemo for this examble
kwame 0 4
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 0 6
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 68 4
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 0 4
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 0 4
WALA NMAN
get pointer 2 6
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 0 4
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 0 5
yep same question what henry asked
Your Name 0 4
kashi.com@gmail.com
Will 58 20
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 0 8
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 1 14
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 1 13
asd
Aditya 5 20
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 1 10
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.
uday 15 8
nice article
Murugan 0 6
Mur Mur Mur
sss 17 18
ss
Zeke 2010/11/16 Contact Me7 14
Hi Will,

I don't know old this post is or if you are still answering questions. I was glad to find it, though,

so that I could use Flash to read and then selectively update an existing XML file. Thank you very

much.

I'm having 2 issues:

1) After Flash successfully updates the XML, refreshing the page on the browser and searching/displaying

the changed element(s) still gets me the old info, even though I can actually see the new info within

the XML file itself. I need to close the browser and open a fresh copy to clear the cache. Any tips on

how I can address this with a simple refresh would be greatly appreciated.

2) After opening a fresh copy of the browser, the Flash program cannot successfuly complete the load of

XML file. It seems that extraneous data, about the last 15 lines or so of the XML file, have been

appended at the end after the closing root element tag. Therefore, the XML file is not properly

formatted and can't be loaded in Flash. I can't for the life of me figure out how this happens.

I know this may be difficult to follow. I could email abbreviated versions of the files if you offer to

take a quick look.

My Actionscript code follows your example and I've changed the PHP slightly:

<html>
<body>
<?php
$fh = fopen("testXML2.xml", 'r+') or die("can't open file");
fwrite($fh, $GLOBALS['HTTP_RAW_POST_DATA']);
fclose($fh);
?>
</body>
</html>

I would love to get to the bottom of this soon. Thank you for your time and consideration.
Will 2010/11/17 Contact Me1 13
You should check out my article on disabling caching in AS3:
http://willperone.net/Code/as3nocache.php
Basically just append ?r=random number or timestamp to the url and it won't cache. I'm not sure what the extra data you are talking about is about but feel free to email me: will@andrograde.com
hanna 2011/01/241 14
Its a great thred and post. Hopefully you are still answering questions. I am working on a search function, which has multiple same name nodes for eg:
<content>
<item image="Abigail_call.jpg" name="Abigail" state = "New York">
<value>ms342</value>
<value>ks567</value>
</item>


<item image="Adam_foldes.jpg" name="Adam" state = "New Jersey" >
<value>fg345</value>
<value>ks749</value>
</item>

<item image="Amanda_falco.jpg" name="Amanda" state = "California">
<value>ms346</value>
<value>ks767</value>
<value>ksty</value>
</item>
</content
so I want to access all <value> nodes and search through them. I know how to search if there is ony one node but I am unable to do the multiple same name node.
Also when i tried to run the XML example with your xml and As3, I got htis error" Scene 1, Layer 'Layer 1', Frame 1, Line 30 1084: Syntax error: expecting identifier before colon" am not very good at AS3, so sorry if iam asking something stupid.
Please reply. Thanks a lot in advance
Will 2011/01/25 Contact Me0 12
Yea I need to clean up the example, I wrote it a long time ago. Try doing something like this:
for each (var value:XML in item.value) {
}
Rayann 2011/07/07 Contact Me0 8
That's a mold-breaker. Great tnhiking!
Mahi 2011/08/18 Contact Me0 9
hi
'm new to flex.. i wanna create one task n tiz.. any 1 help me.. plz contact me through mail..
Login - Password Assignment --- >> The first screen should have a small form for username and password and a submit button. The application should access an XML file having the username and password list for various users. Check for the validity of the username and password from the XML file entered by the user and redirect him to the user screen if the credentials are valid. If the credentials are not valid, a message should be displayed saying the credentials are incorrect.

2011/08/190 6
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;
}
}
Mahi 2011/08/25 Contact Me3 10
Hi will,
plz help me... 'm new to flex..........
Login - Password Assignment --- >> The first screen should have a small form for username and password and a submit button. The application should access an XML file having the username and password list for various users. Check for the validity of the username and password from the XML file entered by the user and redirect him to the user screen if the credentials are valid. If the credentials are not valid, a message should be displayed saying the credentials are incorrect.
Mats 2011/09/2711 13
chetanpl 2011/10/10 Contact Me0 11
Hello frinds how r u
Ravi 2011/10/11 Contact Me0 10
There is a problem in download. It is not accessing the grandchild node....node within daughter....how to access it......the age is not displayed.
Ravi 2011/10/11 Contact Me0 13
Thanks Will for the help...this article has helped to learn how to read XML using AS3
pioppypernMom 2011/11/26 Contact Me0 8
Saurabh Seth 2011/12/01 Contact Me0 8
Hey, I need to parse something like this :-

<xsd:element name="Query" type="tns:xn_res_Mngr_dashboardQuery" xmlns:tns="http://www.niku.com/xog/Query" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>

and need to replace tns in type attribute with the value of the attribute named xmlns:tns.

Can you help me out in this???
Chlebek7Minton 2012/01/13 Contact Me0 9
Right now, an individual has to get obtaining curious to understand, how and where? The reply is not really that complex. You are simply meant to keep on becoming fashionable relating to [url=www.uol.com.br]Uol.com.br[/url] supplies regarding [url=www.yahoo.com]Yahoo.com[/url] organization, and also you then will make [url=www.soso.com]Soso.com[/url] most associated with [url=www.yahoo.com]Yahoo.com[/url] revenue weeks. Besides this, more often than not it happens which [url=www.ifeng.com]Ifeng.com[/url] particular stars and other abundant folks employ [url=www.imgur.com]Imgur.com[/url] totes. This sort of hand bags are mostly fresh as well as selling throughout inexpensive price ranges. Consequently deciding on this type of [url=http://www.mulberry-bagoutlet.net]mulberry discounted[/url] handbag discounted choices can be a different selection that can assist you to benefit from [url=www.uol.com.br]Uol.com.br[/url] without [url=www.amazon.co.jp]Amazon.co.jp[/url] need of investing a substantial amount funds.
Soumya Vinod 2012/01/170 9
Found another relatively simpler way to do the same,posted at http://bbso.wordpress.com/2012/01/16/loading-xml-in-flash-as3
gstephane 2012/02/14 Contact Me32 9
Hello,

Sorry for my poor english.

I have this xml file :

<?xml version="1.0" encoding="UTF-8" ?>
<datas>
<data variable="testing" value="true" cast="Boolean" />
<data variable="day" value="Monthday" cast="String" />
</datas>

I want to save modified value, but i don't know the syntax for modifying these value.

I have this script for save :

public function SaveSettings():void {
var outputString:String = '<?xml version="1.0" encoding="utf-8"?>\n';

datasXML = <settings/>;

if(testNeeded == true) {
datasXML.data.variable[testing].@value = 'true';
} else {
datasXML.data.variable[testing].@value = 'false';
}

outputString += datasXML.toXMLString();
outputString = outputString.replace(/\n/g, File.lineEnding);
stream = new FileStream();
stream.open(datasFile, FileMode.WRITE);
stream.writeUTFBytes(outputString);
stream.close();
}

But, the result is not what i want. Thes lines is in defect :

datasXML.data.variable[testing].@value = 'true';
datasXML.data.variable[testing].@value = 'false';

If anyone have the good syntax, i'm interrested.

Thank in advance for your help
gstephane 2012/02/16 Contact Me108 42
Found !

datasXML.data[@variable = 'testing'].@valeur = 'false';
Will 2012/02/162 0
Thanks for sharing the solution gstephane!
gstephane 2012/02/17 Contact Me172 0
The XML i use it's for an configuration file. I use the cast for transform value's in XML into variable :

private var settingsXML:XML; // THE XML
public var testing:Boolean; // Variable needing value

for(var nameVariable:String in xmlFile.data)
{
if(xmlFile.data.@cast[nameVariable] == 'Number')
{
this[xmlFile.data.@variable[nameVariable]] = Number(xmlFile.data.@value[nameVariable]);
}

if(xmlFile.data.@cast[nameVariable] == 'Boolean')
{
if(xmlFile.data.@value[nameVariable] == 'true')
{
this[xmlFile.data.@variable[nameVariable]] = true;
} else {
this[xmlFile.data.@variable[nameVariable]] = false;
}
}

if(xmlFile.data.@cast[nameVariable] == 'String')
{
this[xmlFile.data.@variable[nameVariable]] = String(xmlFile.data.@value[nameVariable]);
}
}
Henry 2012/09/11 Contact Me0 0
Hi there I am so thrilled I found your blog page, I rellay found you by accident, while I was browsing on Bing for something else, Nonetheless I am here now and would just like to say kudos for a tremendous post and a all round entertaining blog (I also love the theme/design), I don’t have time to browse it all at the minute but I have saved it and also added your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the excellent work.
Will 2012/09/200 0
Thanks!
baba ranchor das 2013/01/29 Contact Me0 0
hiiiii
baba ranchor das 2013/01/29 Contact Me144 0
bal chaler site????????..................
Optiftinc 2013/02/13 Contact Me0 0
Best of the Best!
[url=http://google.com]Best[/url]

d646d646nad646naegddgdHnLeHnLnaeHnL
Garrett 2013/09/13 Contact Me1 1
I know this is an old post but I am running into a bit of a quandary and was hoping you could assist. I have a large list (1700) with company name, program and state. I need to parse out the state data depending on which state is selected, and populate a list with the Company Name.

ADRIAN 2013/11/07 Contact Me0 0
Appreciating the dedication you put into your website and in depth information you offer. It's good to come across a blog every once in a while that isn't the same outdated rehashed information. Wonderful read! I've saved your site and I'm adding your RSS feeds to my Google account.
ADRIAN http://www.discounttomsshoes.net
Anas 2014/02/061 0
Thamks :)

<- for private contact