ArrayCollection to XML in ActionScript3
As I was searching the web trying to find out how to do this all I found was the opposite scenario, XML to an arrayCollection. When I finally did find a bulletin board post on this, all it said was, “LOL. Everyone always asks this.” That wasn’t so helpful so I figured I would write something up.
This is based on a hypothetical application where you enter information of people that pledge an amount of money for some sort of charity. You just enter a name, phone, and amount and it adds the data into an arrayCollection that is displayed in a datagrid. From there you hit a button to create a PDF — no databases involved. They just want a print out.
I know this would never happen with this kind of application in the real world but I had a different scenario where the data didn’t need to be stored and it seemed like a waste to store the data in a database just to go get it again, create a PDF, and then delete the data.
My example function assumes you have an arrayCollection called “acPledges”. You can find everything you need to know about that the bottom of this page (their arrayCollection is called “ac”): http://www.adobe.com/devnet/flex/quickstart/using_data_providers/
private function sendFormAndXML():void {
// Define the Root container and an XML list to go in it
var myXML:XML = <PledgeList></PledgeList>;
var myXMLList:XMLList = new XMLList;
// Loop over arrayCollection adding pledge data to the XML Root
for(var i:int;i<acPledges.length;i++) {
myXMLList = XMLList('<Pledge><Name>'+acPledges[i].name+'</Name>
<Phone>'+acPledges[i].phone+'</Phone>
<Amount>'+acPledges[i].amount+'</Amount></Pledge>');
myXML.appendChild(myXMLList);
}
//Export data as form
var url:String = "myPageThatCreatesPDF.cfm"; //url where the form is going
var variables:URLVariables = new URLVariables();
variables.userName = txtUserName.text;
variables.totalAmount = totalPledgeAmount;
variables.totalQuantity = totalPledgeQuantity;
variables.xmlPledgeData = myXML.valueOf();
var request:URLRequest = new URLRequest(url);
request.method = URLRequestMethod.POST
request.data = variables;
navigateToURL(request);
}
Whether you’re using ColdFusion, PHP, or whatever type of page that the data is sent to, the variables are treated just like posted form data. I’ll save showing how to parse the XML in ColdFusion for another blog post.











Leave your response!