by Christian Cantrell

 Comments (3)

Created

October 23, 2009

E4X makes working with XML in ActionScript extremely simple. Creating some XML is as easy as this:

var inventory:XML =
<inventory>
<product id="111" price="2999.99">Laptop</product>
</inventory>;

But what if you want to generate the XML dynamically and use variables as attribute values or text nodes? Just use curly braces like this:

var products:Array = new Array();

products.push({name:"Laptop", id:111, price:2999.99});
products.push({name:"Mouse", id:222, price:49.99});
products.push({name:"Phone", id:333, price:199.99});

var inventory:XML = <inventory/>;

for each (var o:Object in products)
{
inventory.appendChild(<product id={o.id} price={o.price}>{o.name}</product>);
}

The resulting XML is exactly what you’d expect:

<inventory>
<product id="111" price="2999.99">Laptop</product>
<product id="222" price="49.99">Mouse</product>
<product id="333" price="199.99">Phone</product>
</inventory>

Simple and elegant!

COMMENTS

  • By Jonnie - 9:35 AM on October 23, 2009   Reply

    One thing to note is the toll dynamically generating XML takes on speed. In your example, it would be twice as fast to generate an XML String first, then convert it to XML using: inventory = new XML (xmlString); Some examples show up to 200x speed increases when converting a string to XML: http://jacksondunstan.com/articles/387

  • By stevex - 7:11 PM on October 24, 2009   Reply

    Does this mechanism take care of escaping characters that wouldn’t otherwise be valid in XML?

  • By dVyper - 9:06 AM on October 26, 2009   Reply

    And very slow compared to building it yourself:http://jacksondunstan.com/articles/387

ADD A COMMENT