« My MAX Presentation is Online: What's Coming in AIR 2.0 | Main | Referencing ActionScript Reserved Words in E4X »

October 23, 2009

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!

Posted by cantrell at October 23, 2009 9:08 AM

Comments

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

Posted by: Jonnie at October 23, 2009 9:35 AM

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

Posted by: stevex at October 24, 2009 7:11 PM

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

Posted by: dVyper at October 26, 2009 9:06 AM




Remember Me?

(you may use HTML tags for style)