Home > OS >  How to add informations to my xml - AS3 - AIR
How to add informations to my xml - AS3 - AIR

Time:09-17

I'm loading an xml file name animals.xml

var urlLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE,onXMLLoaded);
var file:File = File.documentsDirectory.resolvePath("animals.xml");
var stream:FileStream = new FileStream();  
urlLoader.load(new  URLRequest(file.url));
 
function onXMLLoaded(e:Event):void{
       xml =  new XML(e.target.data);
     trace(xml..animal.@name[2]);
}

when I click on a button, it modifies the name of the cat by Garfield

click_btn.addEventListener(MouseEvent.CLICK, btn_clicked, false, 0, true);

function btn_clicked(event:MouseEvent):void {
    modifyName();
}
 
function modifyName():void{
    xml..animal.@name[2] = "GARFIELD";
    stream.open(file, FileMode.WRITE);
stream.writeUTFBytes(xml);
stream.close();
}

How can I, now, add new information to my xml ?

My XML is build like that :

<?xml version="1.0" encoding="UTF-8"?>
<animals>
        <animal  type="dog" name="Fido" age="2">Fido is a good  dog.</animal>
        <animal  type="dog" name="Ralph" age="1">Ralph is  brown.</animal>
        <animal  type="dog" name="Brian" age="1">Brian is  Ralph's brother.</animal>
        <animal  type="cat" name="Charlie" age="3">Charlie  likes fish.</animal>
      <animal type="rabit" name="Gulper" age="3">Gulper does  not want to be eaten.</animal>
</animals>

How do I do to add a new line ? For example :

animal type ="turtle"
name "Caroline"
age = "5"
Caroline is a turtle 

So, in the results, I'll have :

            <animal  type="dog" name="Fido" age="2">Fido is a good  dog.</animal>
            <animal  type="dog" name="Ralph" age="1">Ralph is  brown.</animal>
            <animal  type="dog" name="Brian" age="1">Brian is  Ralph's brother.</animal>
            <animal  type="cat" name="Charlie" age="3">Charlie  likes fish.</animal>
          <animal type="rabit" name="Gulper" age="3">Gulper does  not want to be eaten.</animal>
 <animal  type="turtle" name="Caroline" age="5"> Caroline is a turtle </animal>
    </animals>

CodePudding user response:

You need to add a new child node to your XML. Something like that:

function addAnimal(target:XML, type:String, name:String, age:int, comment:String):void
{
    target.appendChild(<animal type={type} name={name} age={age}>{comment}</animal>);
}

The idea behind curly brackets is to simplify XML node notation. Should be quite transparent by itself, but if you are curious, you may start looking it up from here.

Then, you free to add as many animals as you need:

addAnimal(xml, "turtle", "Caroline", 5, "Caroline is a turtle");
addAnimal(xml, "peacock", "Lord Chen", 25, "Must build a cannon");
  • Related