How to read and write an XML file in Adobe AIR or Flex?

By | August 24, 2012

AIR treats the XML files as just as normal file and so you can proceed using the FileStream classs. Please take a look at the sample code. Just copy and paste the following code to your main.MXML file and you are done.

  import flash.xml.XMLDocument;

  private function init():void
  {
   xmlTA.text = " Sample XML ";
   var fileStream:FileStream = new FileStream();
   var prefsXML:XML =
           Sample
           XML
        ;

   var file:File = File.applicationStorageDirectory.resolvePath("preferences.xml");
   fileStream = new FileStream();
   fileStream.open(file, FileMode.WRITE);

   var outputString:String = 'n';
   outputString += prefsXML.toXMLString();

   fileStream.writeUTFBytes(outputString);
   fileStream.close();

   /* Reading the XML File */
   file = File.applicationStorageDirectory.resolvePath("preferences.xml");
   fileStream.open(file, FileMode.READ);
   prefsXML= XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
   readTA.text = prefsXML;
   fileStream.close();

   /*
    The previous examples use FileStream objects opened for synchronous operation.
    You can also open files for asynchronous operations (which rely on event listener functions to respond to events).
    For example, the following code shows how to read an XML file asynchronously:
   */

   file = File.applicationStorageDirectory.resolvePath("preferences.xml");
   fileStream = new FileStream();
   fileStream.addEventListener(Event.COMPLETE, processXMLData);
   fileStream.openAsync(file, FileMode.READ);

   function processXMLData(event:Event):void
   {
       prefsXML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
       asyXML.text = prefsXML;
       fileStream.close();
   }

  }
 ]]>

Please post your comments on this post

Leave a Reply

Your email address will not be published. Required fields are marked *