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:

  1. import flash.filesystem.File;
  2. import flash.filesystem.FileStream;
  3. import flash.filesystem.FileMode;
  4. import flash.events.Event;
  5.  
  6. /* Determine Path of Loaded and Saved File */
  7. var appDirectory:File = File.applicationStorageDirectory
  8. var newFileStream:FileStream = new FileStream();
  9. var fileString:String = appDirectory.nativePath;
  10. var appFile:File = File.documentsDirectory;
  11. 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

  1. /* LOAD XML */
  2. var xmlString:URLRequest = new URLRequest(fileString+"\data.xml");
  3. var xmlLoader:URLLoader = new URLLoader(xmlString);
  4. xmlLoader.addEventListener("complete", init);
  5. var defaultXML:XMLDocument = new XMLDocument();
  6.  
  7. /* INIT DATA */
  8. function init(event:Event):void {
  9. var xml:XML = XML(xmlLoader.data); // Loads the XML data in to the variable "xml"
  10. }
  11.  
  12. /* Save the modified data to the xml file. */
  13. function saveData(e:Event):void
  14. {
  15. newFileStream.openAsync (appFile, FileMode.WRITE);
  16. var xml:XML = XML(xmlLoader.data);
  17. xml.newElement = ; // Here you can add a new element in to the XML list
  18. newFileStream.writeUTFBytes(xml);
  19. newFileStream.close ();
  20. }
/* 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.

Leave A Comment