Saving XML file in AS3 is possible


var xml:XML = <myXml>
                    <item prop="1" />
                    <item prop="2" />

I need to save as xml file in local harddisk(project directory).

Is it possible to save in as3 itself?

Best Solution

I threw this together, and sure enough you can save to .XML using the following as a minimalist example.

package com.hodgedev.xmlcreator
    import flash.display.Sprite;
    import flash.utils.ByteArray;

 * ...
 * @author Brian Hodge (
public class Main extends Sprite 
    private var _xml:XML;

    public function Main():void 
        if (stage) init();
        else addEventListener(Event.ADDED_TO_STAGE, init);

    private function init(e:Event = null):void 
        removeEventListener(Event.ADDED_TO_STAGE, init);

        //Calling the save method requires user interaction and Flash Player 10
        stage.addEventListener(MouseEvent.MOUSE_DOWN, _onMouseDown);

        _xml= <xml>
    private function _onMouseDown(e:MouseEvent):void
        var ba:ByteArray = new ByteArray();

        var fr:FileReference = new FileReference();
        fr.addEventListener(Event.SELECT, _onRefSelect);
        fr.addEventListener(Event.CANCEL, _onRefCancel);, "filename.xml");
    private function _onRefSelect(e:Event):void
    private function _onRefCancel(e:Event):void


There are some things to note.

  • You require Flash Player 10 to use the save method of the FileReference class.
  • In order to do anything that INVOKES a prompt, Flash requires user interaction like keyboard or mouse input.

In the above I listen for MouseEvent.MOUSE_DOWN on the stage to serve as the USER INTERACTION which is required to invoke the save prompt.

I setup a basic XML structure within the code (this will typically come from and external source and will work fine both ways.

A ByteArray is created and the XML is written to the ByteArray.

The save method of the FileReference class requires a ByteArray and default save name be passed as the two parameters.

I hope this helps.

Related Question