Generating Dynamic XML With E4X in ActionScript

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!