Daniel Love AKA Dr Love

Creative Technologist and Solution Architect: development, research, business process, and consulting.

 
Parsing XML to an object

E4X is a solution that adds native XML support to ActionScript 3.

Previously in ActionScript 2 parsing XML consisted of lots of iteration and unreadable messy code (Unless you used XPath of course, and then it's only slightly unpleasant).
Although the aforementioned statement is not so with E4X, extremely powerful and easy.
E4X allows you to treat your XML document as an Object, using the standard dot notation to access children and attributes of any given node within a XML document.

Here's the XML we will be parsing into an object during this example.

<xml>
	<datalist>
		<header><![CDATA[This is some header text]]></header>
		<body><![CDATA[This is some random body text]]></body>
		<linktext><![CDATA[Visit my blog]]></linktext>
		<linkurl><![CDATA[http://www.daniellove.net/blog]]></linkurl>
	</datalist>
</xml>
				

The XML is pretty simple, but I may post a more advanced example in another post and explain a few more E4X operations. Below is the ActionScript that will parse the XML and output it as an object.

// this is the object that contains the parsed xml
var objParsedXml : Object;
objParsedXml = new Object ( );
 
// _xml is the XML document above
var xmlData : XMLList;
xmlData = _xml.dataList;
 
var numChildren : Number;
numChildren = xmlData.children ( ).length ( );
 
var i : Number;
i = 0;
 
for ( ; i < numChildren; i++ )
{
	var strNodeName : String;
	var strNodeValue : String;
 
	// Get the name of the node value
	strNodeName = xmlData.children ( ) [ i ].name ( );
 
	// Get the value of the node value
	strNodeValue = xmlData.children ( ) [ i ];
 
	// Add the name of the node as a property of the object.
	// Add the value of the node as the value of the property
	objParsedXml [ strNodeName ] = strNodeValue;
}
				

In order to test that the XML was parsed correctly, you can enumerate through the object. See this post regarding enumerating of objects.

The above XML, once parsed to an Object should output as the following once enumerated using the above method:

header: This is some header text
body: This is some random body text
linktext: Visit my blog
linkurl: http://www.daniellove.net/blog
				
Adobe, ActionScript, Tutorial
Monday 02nd June, 2008, 11:32 PM. Daniel Love. Copyright 2009 ©
 

Name/Alias

Email (will not be displayed, required)

Website (optional)

Twitter (optional)

LinkedIn (optional)

Comment