Dynamically add element / attribute to a XML using E4X

September 25, 2008 at 12:01 pm (Flex, XML) (, , )

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

Permalink 3 Comments

Article: Introducing E4X

August 10, 2008 at 9:21 pm (Flex, XML) (, , , )

Found a great article on E4X by Kurt Cagle. Below is the link.

Introducing E4X

Permalink 1 Comment