Saturday, May 7, 2011

How to Read and Write XML files with Flex and AIR

Needed Resources:

Final Product:
An AIR application with a load xml and save xml button. The load button prompts the user to find an xml file titled "person.xml." Once the user has selected the file, the first name and last name of the person will be displayed in two text inputs. The user can then edit these entries and save them back to the file using the save button.
The Data:
<?xml version="1.0" encoding="UTF-8"?>
<person>
<firstName>John</firstName>
<lastName>Doe</lastName>
</person>

Execution:
  1. Mock up a simple interface with two input fields and two buttons in MXML:

    <mx:VBox>
    <mx:HBox>
    <mx:Label text="First Name:"/>
    <mx:TextInput id="fName_txti"/>
    </mx:HBox>
    <mx:HBox>
    <mx:Label text="Last Name:"/>
    <mx:TextInput id="lName_txti"/>
    </mx:HBox>
    <mx:HBox>
    <mx:Button id="load_btn" label="Load XML" click="loadXML()"/>
    <mx:Button id="save_btn" label="Save XML" click="saveXML()" enabled="false"/>
    </mx:HBox>
    </mx:VBox>
    NOTE: save_btn is disabled to prevent the user from trying to save something that does not yet exist.
  2. Create a script tag and import the Alert class that will be needed to let the user know if they have selected an invalid file:
    import mx.controls.Alert;
  3. Write the method that will be invoked when the"Load XML" button is clicked:

    private function loadXML():void{
    file = new File();
    file.addEventListener(Event.SELECT, dirSelected);
    file.browseForOpen("Select person.xml file");
    }
  4. Setup the event listener function that will read the xml file and create an XML object. If the user has not picked a file with the name "person.xml," the application will fire a prompt informing them of their mistake:

    private function dirSelected(e:Event):void {

    if(file.nativePath.indexOf("person.xml") != -1){
    var fs:FileStream = new FileStream();
    fs.open(file, FileMode.READ);
    personXML = XML(fs.readUTFBytes(fs.bytesAvailable));
    fs.close();
    setTextInputs();
    }else{
    Alert.show("You have not selected an xml file called 'person.xml'");
    }
    }
  5. The next function is a helper function that sets the text input's text:

    private function setTextInputs():void{
    fName_txti.text = personXML.firstName;
    lName_txti.text = personXML.lastName;
    save_btn.enabled = true;
    }
  6. Last is the function to save the xml back to the originally opened file:

    private function saveXML():void{
    personXML.firstName = fName_txti.text;
    personXML.lastName = lName_txti.text;
    var newXMLStr:String = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + personXML.toXMLString();
    var fs:FileStream = new FileStream();
    fs.open(file, FileMode.WRITE);
    fs.writeUTFBytes(newXMLStr);
    fs.close();
    }
    NOTE: If the application used "writeUTF" instead of "writeUTFBytes" the xml file ends up with some garbage characters that causes parse errors when the app tries to reopen and parse the xml.
  7. Check out this post to see how to save a class object to XML. Enjoy!

No comments:

Post a Comment