Example: Reading an XML file into an XML object

Adobe AIR 1.0 and later

The following examples demonstrate how to read and write to a text file that contains XML data.

To read from the file, initialize the File and FileStream objects, call the readUTFBytes() method of the FileStream and convert the string to an XML object:

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

Similarly, writing the data to the file is as easy as setting up appropriate File and FileStream objects, and then calling a write method of the FileStream object. Pass the string version of the XML data to the write method as in the following code:

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

These examples use the readUTFBytes() and writeUTFBytes() methods, because they assume that the files are in UTF-8 format. If not, you may need to use a different method (see Data formats, and choosing the read and write methods to use ).

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:

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

The processXMLData() method is invoked when the entire file is read into the read buffer (when the FileStream object dispatches the complete event). It calls the readUTFBytes() method to get a string version of the read data, and it creates an XML object, prefsXML , based on that string.

To see a sample application that shows these capabilities, see Reading and writing from an XML preferences file .

To see a sample application that shows these capabilities, see Reading and writing from an XML Preferences File .

// Ethnio survey code removed