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 =
<product id="111" price="2999.99">Laptop</product>

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={} price={o.price}>{}</product>);

The resulting XML is exactly what you’d expect:

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

Simple and elegant!

3 Responses to Generating Dynamic XML With E4X in ActionScript

  1. Jonnie says:

    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:

  2. stevex says:

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

  3. dVyper says:

    And very slow compared to building it yourself: