Sunday, September 19, 2010

Working with XML data using AS3: Part 10

In this tutorial we will learn how to save an AS3-created XML file on user's computer.

In the previous tutorial we've learned how to create XML data using AS3. Today we will let the user store this data as an .xml file on their computer.

We will use FileReference.save(); which is a very handy method. It has 2 parameters - the first one is the path to the data we want to save, the second is the default name that the file will be saved with (user is able to change this name).

Here is an example of what we're going to create:


First of all we create our data.

var _data:XML = 
<contactlist>
<contact>
<myTag>John</myTag>
<lastName>Jackson</lastName>
<age>21</age>
</contact>
<contact>
<myTag>Gregory</myTag>
<lastName>Armstrong</lastName>
<age>23</age>
</contact>
<contact>
<myTag>Richard</myTag>
<lastName>Black</lastName>
<age>30</age>
</contact>
</contactlist>

trace("My XML object: \n" + "------------------ \n" + _data);

To use File Reference, we need to import it in the beginning of the code.

import flash.net.FileReference;

I have put a button on the stage called saveBtn. It opens the save window.

var fileReference:FileReference = new FileReference();

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

saveBtn.addEventListener(MouseEvent.CLICK, saveData);

Now, I will explain.

FileReference is able to save files of different extensions. If the data passed is String, it will be saved in the .txt format, XML - .xml format. It is also possible to save pictures, but you will need to use encoders (for the correct data format to pass to the FileReference.save method), but this tutorial is not about pictures.

The full code:

import flash.net.FileReference;

var _data:XML = 
<contactlist>
<contact>
<myTag>John</myTag>
<lastName>Jackson</lastName>
<age>21</age>
</contact>
<contact>
<myTag>Gregory</myTag>
<lastName>Armstrong</lastName>
<age>23</age>
</contact>
<contact>
<myTag>Richard</myTag>
<lastName>Black</lastName>
<age>30</age>
</contact>
</contactlist>

trace("My XML object: \n" + "------------------ \n" + _data);

var fileReference:FileReference = new FileReference();

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

saveBtn.addEventListener(MouseEvent.CLICK, saveData);

Thanks for reading!

Related:

Working with XML data using AS3: Part 1
Working with XML data using AS3: Part 2
Working with XML data using AS3: Part 3
Working with XML data using AS3: Part 4
Working with XML data using AS3: Part 5
Working with XML data using AS3: Part 6
Working with XML data using AS3: Part 7
Working with XML data using AS3: Part 8
Working with XML data using AS3: Part 9

No comments:

Post a Comment