Friday, February 25, 2011

Working with CSV files using AS3: Part 5

Today we will once again parse CSV to XML using AS3, but using a different method to create the XML this time.

Everything except for the XML creation part of the script is the same as in the previous tutorial.

Here is how we handle generating the XML object this time:

var myXml:XML = <myxml></myxml>

for (var u:int=0; u<loadedData.length; u++){
myXml.appendChild(<person/>);
myXml.person[u].@id = loadedData[u].ID;
myXml.person[u].@first = loadedData[u].First;
myXml.person[u].@last = loadedData[u].Last;
myXml.person[u].@job = loadedData[u].Job;
}

As you can see, we first create an XML object and add parent nodes to it. After that we have a loop, where we append childs and set each attribute separately. This way we don't need any temporary strings to make the XML - everything is written straight into the object.

And 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);
myLoader.load(myRequest);

function onload(Event):void
{
loadedData = myLoader.data.split(/\r\n|\n|\r/);
loadedData.pop();
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]};
}
loadedData.shift();

var myXml:XML = <myxml></myxml>

for (var u:int=0; u<loadedData.length; u++){
myXml.appendChild(<person/>);
myXml.person[u].@id = loadedData[u].ID;
myXml.person[u].@first = loadedData[u].First;
myXml.person[u].@last = loadedData[u].Last;
myXml.person[u].@job = loadedData[u].Job;
}

import flash.net.FileReference;

var fileReference:FileReference = new FileReference();

function saveData(MouseEvent):void{
fileReference.save(myXml, "example.xml");
}

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

Once again, you need a button (component) called saveBtn on stage, and it will be enabled when XML is created and ready to be saved on the user's hard drive.

Thank you for reading!

Related:

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 4

2 comments:

Ernest Klúčik said...

Hi, really thanks for great tutorial. Can i have a question? this automatically load csv file and than user can save it as XML.

Is there some way to this way: dialog open => user select and load XML file => now we can work with it normally => after that user can save it again to XML file.

Can i modify this actionscript i need to find another way?

Kirill Poletaev said...

If you're using AIR, use the File class' browseForOpen() method. You can use AS3 FileReference class' browse() method too.

Post a Comment