Written for: Flex, ActionScript 3.0
To dynamically add element / attribute to a XML; assume that it already exists in the XML and using the .(dot) operator, pass a value to it.
Here’s an example. Consider the following XML:
var albumXML:XML =
<tracks>
<song tracknumber="1">
<title>Orgasm Addict</title>
<artist>Buzzcocks</artist>
</song>
<song tracknumber="2">
<title>What Do I Get?</title>
<artist>Buzzcocks</artist>
</song>
<song tracknumber="3">
<title>I Dont Mind</title>
<artist>Buzzcocks</artist>
</song>
<song tracknumber="4">
<title>Love You More</title>
<artist>Buzzcocks</artist>
</song>
</tracks>;
To add an additional element of <genre> to the first <song> node, I’ll use the following line of code.
albumXML.song[0].genre = 'Punk';
Similarly to add an attribute of duration to the first <song> node, I’ll use.
albumXML.song[0].@duration = '2:00';
Now if you trace the XML file, it’ll show as:
trace(albumXML);
/*
<tracks>
<song tracknumber="1" duration="2:00">
<title>Orgasm Addict</title>
<artist>Buzzcocks</artist>
<genre>Punk</genre>
</song>
<song tracknumber="2">
<title>What Do I Get?</title>
<artist>Buzzcocks</artist>
</song>
<song tracknumber="3">
<title>I Dont Mind</title>
<artist>Buzzcocks</artist>
</song>
<song tracknumber="4">
<title>Love You More</title>
<artist>Buzzcocks</artist>
</song>
</tracks>
*/
Additionally, you can use the following methods of a XML object.
- appendChild()
- prependChild()
- insertChildAfter()
- insertChildBefore()