Adobe Air and Save XML in a local File
In my earlier post I talked about loading local or online XML data. But how about saving. Since it is nice to save settings for an App. Here is my solution:
- import flash.filesystem.File;
- import flash.filesystem.FileStream;
- import flash.filesystem.FileMode;
- import flash.events.Event;
- /* Determine Path of Loaded and Saved File */
- var appDirectory:File = File.applicationStorageDirectory
- var newFileStream:FileStream = new FileStream();
- var fileString:String = appDirectory.nativePath;
- var appFile:File = File.documentsDirectory;
- appFile = appFile.resolvePath(fileString+"\data.xml");
import flash.filesystem.File; import flash.filesystem.FileStream; import flash.filesystem.FileMode; import flash.events.Event; /* Determine Path of Loaded and Saved File */ var appDirectory:File = File.applicationStorageDirectory var newFileStream:FileStream = new FileStream(); var fileString:String = appDirectory.nativePath; var appFile:File = File.documentsDirectory; appFile = appFile.resolvePath(fileString+"\data.xml");
This code uses a local file called data.xml in the applicationStorageDirectory.
In Windows it is stored here: //C:Users{username}AppDataRoaming{ProjectName}Local Store
- /* LOAD XML */
- var xmlString:URLRequest = new URLRequest(fileString+"\data.xml");
- var xmlLoader:URLLoader = new URLLoader(xmlString);
- xmlLoader.addEventListener("complete", init);
- var defaultXML:XMLDocument = new XMLDocument();
- /* INIT DATA */
- function init(event:Event):void {
- var xml:XML = XML(xmlLoader.data); // Loads the XML data in to the variable "xml"
- }
- /* Save the modified data to the xml file. */
- function saveData(e:Event):void
- {
- newFileStream.openAsync (appFile, FileMode.WRITE);
- var xml:XML = XML(xmlLoader.data);
- xml.newElement = ; // Here you can add a new element in to the XML list
- newFileStream.writeUTFBytes(xml);
- newFileStream.close ();
- }
/* LOAD XML */
var xmlString:URLRequest = new URLRequest(fileString+"\data.xml");
var xmlLoader:URLLoader = new URLLoader(xmlString);
xmlLoader.addEventListener("complete", init);
var defaultXML:XMLDocument = new XMLDocument();
/* INIT DATA */
function init(event:Event):void {
var xml:XML = XML(xmlLoader.data); // Loads the XML data in to the variable "xml"
}
/* Save the modified data to the xml file. */
function saveData(e:Event):void
{
newFileStream.openAsync (appFile, FileMode.WRITE);
var xml:XML = XML(xmlLoader.data);
xml.newElement = ; // Here you can add a new element in to the XML list
newFileStream.writeUTFBytes(xml);
newFileStream.close ();
}If you have questions or a better solution. let me know.