Thursday, February 24, 2011

Working with CSV files using AS3: Part 4

In this tutorial we will create a CSV to XML parser using AS3, and we'll be able to save the XML file to hard drive.

Firstly, create a button component and put it on stage, give it a name of saveBtn. It will be disabled on start, and enabled once CSV is parsed to XML and we are ready to save the file. This usually takes milliseconds.

Here is the full code:

saveBtn.enabled = false;

var myRequest:URLRequest = new URLRequest("example.csv");
var loadedData:Array = [];
var myLoader = new URLLoader();
myLoader.addEventListener(Event.COMPLETE, onload);

function onload(Event):void
loadedData =\r\n|\n|\r/);
for (var i:int=0; i<loadedData.length; i++){
var rowArray:Array = loadedData[i].split(",");
loadedData[i] = {ID: rowArray[0], First: rowArray[1], Last: rowArray[2], Job: rowArray[3]};

var xmlStr:String = "<myxml>"
for (var u:int=0; u<loadedData.length; u++){
xmlStr += "<person id='" + loadedData[u].ID + "' first='" + loadedData[u].First + "' last='" + loadedData[u].Last + "' job='" + loadedData[u].Job + "' />";
xmlStr += "</myxml>"

var myXml:XML = new XML(xmlStr);


var fileReference:FileReference = new FileReference();

function saveData(MouseEvent):void{, "example.xml");

saveBtn.addEventListener(MouseEvent.CLICK, saveData);
saveBtn.enabled = true;

Just like in the previous tutorial, we turn the CSV data into an array. Now, we turn the array into an XML object by creating a string and then applying it to the XML variable. The file reference part of the code allows us to save the file on the computer.

And that's it for now.

Thanks for reading!


Working with CSV files using AS3: Part 1
Working with CSV files using AS3: Part 2
Working with CSV files using AS3: Part 3
Working with CSV files using AS3: Part 5

No comments:

Post a Comment