如何将信息添加到我的 xml - AS3 - AIR

How to add informations to my xml - AS3 - AIR

我正在加载 xml 文件名 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]);
}

当我点击一个按钮时,它修改了加菲猫的名字

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();
}

我现在如何向我的 xml 添加新信息?

我的 XML 是这样构建的:

<?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>

如何添加新行? 例如:

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

所以,在结果中,我将有:

            <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>

您需要向 XML 添加一个新的子节点。类似的东西:

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

花括号背后的想法是简化 XML 节点符号。本身应该是相当透明的,但是如果你好奇的话,你可以从here.

开始查找

然后,您可以随意添加任意数量的动物:

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