Home > AIR (Apollo) Tutorial, ActionScript 3.0 Tutorial > Loading and Saving External XML Data in AIR (Apollo)

Loading and Saving External XML Data in AIR (Apollo)

I just finished an AIR (Apollo) application that loads and saves data from an external XML file. I figured I would share the code to accomplish this task as there is not a lot of Apollo info around at this time.

First off lets start with loading an XML file and reading its contents. I realize that there are much easier ways to load XML into Flash than this, but the advantage here is that I can use File.applicationResourceDirectory which allows me to target the installation directory for the XML file that was included with the AIR package. In this snippet I am using the synchronous open method. This essentially pauses everything else in the Flash movie until it has completed its task (opening the file).


import flash.filesystem.*;

private var _data:String; // Data string pulled from the xml file.

/**
 * Load the xml file and read its data.
 */
private function loadData():void
{
  var dataFile:File = File.applicationResourceDirectory.resolve("data.xml");
  var stream:FileStream = new FileStream();
  stream.open(dataFile, FileMode.READ);
  _data = stream.readUTFBytes(stream.bytesAvailable);
  stream.close();
}

This next snippet shows how to save data to a file using the asynchronous openAsync method. The asynchronous methods allow Flash to continue running normally and use events to trigger user specified actions.


private var _dataXML:XML;	// The XML data.

/**
 * Save the modified data to the xml file.
 */
private function saveData():void
{
  var dataFile:File = File.applicationResourceDirectory.resolve("data.xml");
  var stream:FileStream = new FileStream();
  stream.openAsync(dataFile, FileMode.WRITE);
  stream.writeUTFBytes(_dataXML);
  stream.addEventListener(Event.CLOSE, onDataSaved);
  stream.close();
}

/**
 * Called when the data has been successfully saved.
 * Load the saved data back into the application.
 */
private function onDataSaved(event:Event):void
{
  loadData();
}

If you are planning on using AIR (Apollo) for your own projects I would highly recommend reading Apollo for Adobe Flex Developers Pocket Guide by Mike Chambers, Robert L. Dixon & Jeff Swartz.

  1. Nolan
    August 7th, 2007 at 11:31 | #1

    Awesome little tutorial. This is exactly what I’ve been looking for.

    Thanks!

  2. December 16th, 2007 at 12:51 | #2

    Great tutorial and outstanding website……..thanks

  3. May 27th, 2008 at 18:13 | #3

    Thanks for the Great tutorial

  4. January 11th, 2009 at 17:28 | #4

    Great tut. Thanks for XML file, Just started working with Air. Thnx for the link to the pocket file as well:) Sharon

  1. No trackbacks yet.