Working with XML in AS3 is really easy, so to expand on TheDarkIn1978's answer with some code:
Creating an XML object:
var objs:XML = new XML( <objects /> ); // create the <objects /> node
// for your objects
var ball1:XML = new XML ( <ball /> ); // create the <ball /> node
ball1.@xPos = 12; // add 12 as an attribute named "xPos"
ball1.@yPos = 42; // add 42 as an attribute named "yPos"
objs.appendChild( ball1 ); // add the <ball> node to <objects>
// an example of using variables in your xml
var name:String = "something";
var sx:XML = new XML( <{name} /> ); // creates a node <something />
Use the TheDarkIn1978's to the XML
class in AS3 to learn more.
Saving out your file:
// saving out a file
var f:FileReference = new FileReference;
f.save( sx, "myXML.xml" ); // saves under the name myXML.xml, "sx" being your root XML node
Compressing your XML before saving (with large XML files, this can save a lot):
// compressing before saving
var f:FileReference = new FileReference;
var bytes:ByteArray = new ByteArray;
bytes.writeUTFBytes( myXML ); // "myXML" being your root XML node
bytes.compress(); // compress it
f.save( bytes, "myXML.xml" );
Loading in a compressed XML, uncompressing it, and retrieving the XML object:
// uncompressing a compressed xml
var loader = new URLLoader;
loader.dataFormat = URLLoaderDataFormat.BINARY;
// listen for our events
loader.addEventListener( Event.COMPLETE, this._onLoad );
loader.addEventListener( IOErrorEvent.IO_ERROR, this._onFail ); // not shown
loader.addEventListener( SecurityErrorEvent.SECURITY_ERROR, this._onSecurityError ); // not shown
private function _onLoad( e:Event ):void
{
var loader:URLLoader = e.target as URLLoader;
// get the data as a bytearray
var ba:ByteArray = loader.data as ByteArray;
// uncompress it
try
{
ba.uncompress();
}
catch ( e:Error )
{
trace( "The ByteArray wasn't compressed!" );
}
// get our xml data
myXML = XML( ba );
}
I created a simple tool for compressing/uncompressing XML files. You can get the SWF and source at http://divillysausages.com/blog/xml_compressor_uncompressor if you're interested
Best Solution
I threw this together, and sure enough you can save to .XML using the following as a minimalist example.
}
There are some things to note.
FileReference
class.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 theByteArray
.The save method of the
FileReference
class requires aByteArray
and default save name be passed as the two parameters.I hope this helps.