TDOT Blog Touchwood Creative

Register | Forgot password?

Author Info

Name
Ben Bishop

Job Title
Senior Interactive Developer



Touchwood is continuing to grow!

We are looking for talented Flex developers to join our Interactive Group. If you have any interest we would love to meet you. Please email your resume to us at:

jobs@touchwoodcreative.com


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!
AttachmentSize
XML Reader Writer.zip295.06 KB
person.zip205 bytes

Files

It seems as if your working example is down.

Also, I'm new to this. It says it's also for Flex. But, I can't just paste the code into Flex and compile because I get an error. Any help?

example for datagrid?

Can you post an example like this one except instead of inputting/outputting via a textInput, if you could load it into a dataGrid and edit it and save the changes made in the dataGrid? I've tried using this example using personXML.firstName = fname.dataField, but that hasn't worked for me.

Could you tell me?

How append new record to an exists file?

Could you please tell me how to run your code?

I imported your code to Flex Bulider3, but it doesn't show anything...

Could you please tell me how to run your code?

I imported your code to Flex Bulider3, but it doesn't show anything...

HELP !! :(

Hello,

First, thank you for this script it's very easy to understand.

Unfortunately it doesn't work on my computer, i don't know why, can you help me please.

I downloaded the "WML Reader Writer.zip" and opened it with flex Builder 3 and when i try to run it i have this error :

VerifyError: Error #1014: The classe flash.events::NativeWindowBoundsEvent can't be found.

at flash.display::MovieClip/nextFrame()
at mx.managers::SystemManager/deferredNextFrame()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\managers\SystemManager.as:299]
at mx.managers::SystemManager/preloader_initProgressHandler()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\managers\SystemManager.as:2211]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.preloaders::Preloader/timerHandler()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\preloaders\Preloader.as:398]
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()

ReferenceError: Error #1065: The variable _winMaxButtonStyle__embed_css_win_max_up_png_1895125682 isn't defined

etc.

thank you very much for you help,
bye
J.

getting error

I am following you code and made :
<?xml version="1.0" encoding="utf-8"?>

HTTPService

Just a subtle twist here on your version is that you can still use HTTPService to access XML data as well. Once the user has selected the file, assign myHTTPService.url = file.url and then myHTTPService.send(). Doesn't help you with saving, but you can then use data-binding to put the data in the input fields.

Two cents,
Kevin Hoyt
Platform Evangelist
Adobe Systems, Inc.

Re: HTTPService

Thanks Kevin,
Using the HTTPService is a good idea. It would probably make moving an app from AIR to a browser easier. One would just have to worry about changing the output code instead of both the reading and writing code.

Regards,
Ben

Can I append recoeds to an XML file?

Based on your codes, I try to append codes to an XML file,but it shows"Error #1009: Cannot access a property or method of a null object reference.",
Could you please have a look?

=============================================================
private function appendXML():void{
myButtonInfo.buttonID=BtnID.text;
myButtonInfo.xPosition=xPos.text;
myButtonInfo.yPosition=yPos.text;
myButtonInfo.bWidth=bW.text;
myButtonInfo.bHeight=bH.text;
myButtonInfo.action=bA.text;
var newXMLStr:String="<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+myButtonInfo.toXMLString();
var fs:FileStream=new FileStream();
fs.open(file,FileMode.APPEND);
fs.writeUTFBytes(newXMLStr);
fs.close();
}

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
© Touchwood Creative 2007 | We use Firefox