Вы находитесь на странице: 1из 2

Loading and Saving External XML Data in AIR (Apollo) | Fraser Crosbie - Calgary Flash & Flex Developer

Loading and Saving External XML Data in AIR (Apollo)


July 3rd, 2007 Fraser Crosbie Go to comments Leave a comment

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.
AIR (Apollo) Tutorial, ActionScript 3.0 Tutorial

http://www.flashdev.ca/article/loading-and-saving-xml-data-in-air-apollo/[25/10/2010 12:20:26]

Adobe AIR 1.5 * Ejemplo: Lectura de un archivo XML para ponerlo en un objeto XML

Ejemplo: Lectura de un archivo XML para ponerlo en un objeto XML


Comentarios (0) Los siguientes ejemplos muestran cmo leer y escribir en un archivo de texto que contiene datos XML. Para leer del archivo, inicialice los objetos File y FileStream, llame al mtodo readUTFBytes() del objeto FileStream y convierta la cadena en objeto XML:

var file:File = File.documentsDirectory.resolvePath("AIR Test/preferences.xml"); var fileStream:FileStream = new FileStream(); fileStream.open(file, FileMode.READ); var prefsXML:XML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable)); fileStream.close();

Asimismo, para escribir los datos en el archivo basta con configurar objetos File y FileStream apropiados y luego llamar a un mtodo de escritura del objeto FileStream. Pase la versin en cadena de los datos XML al mtodo de escritura, como en el cdigo siguiente:

var prefsXML:XML = <prefs><autoSave>true</autoSave></prefs>; var file:File = File.documentsDirectory.resolvePath("AIR Test/preferences.xml"); fileStream = new FileStream(); fileStream.open(file, FileMode.WRITE); var outputString:String = '<?xml version="1.0" encoding="utf-8"?>\n'; outputString += prefsXML.toXMLString(); fileStream.writeUTFBytes(outputString); fileStream.close();

En estos ejemplos se utilizan los mtodos readUTFBytes() y writeUTFBytes() porque presuponen que los archivos estn en formato UTF-8. En caso contrario, puede resultar necesario usar otro mtodo (consulte Formatos de datos y eleccin de los mtodos de lectura y escritura). Los ejemplos anteriores utilizan objetos FileStream abiertos para una operacin sincrnica. Tambin se pueden abrir archivos para operaciones asncronas (que dependen de las funciones de deteccin de eventos para responder a los eventos). Por ejemplo, el siguiente cdigo muestra cmo leer un archivo XML de forma asncrona:

var file:File = File.documentsDirectory.resolvePath("AIR Test/preferences.xml"); var fileStream:FileStream = new FileStream(); fileStream.addEventListener(Event.COMPLETE, processXMLData); fileStream.openAsync(file, FileMode.READ); var prefsXML:XML; function processXMLData(event:Event):void { prefsXML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable)); fileStream.close(); }

El mtodo processXMLData() se invoca cuando se lee la totalidad del archivo para ponerlo en el bfer del lectura (cuando el objeto FileStream distribuye el evento complete ). Llama al mtodo readUTFBytes() para obtener una versin en cadena de los datos ledos, y crea un objeto XML, prefsXML , con base en esa cadena.

http://help.adobe.com/es_ES/AIR/1.5/devappsflash/WS5b3ccc516d4fbf351e63e3d118666ade46-7dc5.html[25/10/2010 12:58:09]

Вам также может понравиться