E4X 101 - The Basics
ECMAScript for XML, or E4X, is a new native way for working with XML documents in ActionScript 3.0 and JavaScript 1.6 (Firefox 1.5+). Prior to E4X, you needed to use DOM methods for navigating and building XML documents.
Before we get started, we need a few things:
Once you have Flex setup, create a new ActionScript project. Use my previous post to setup the XML load mechanism. Once all that is done, we can finally start experimenting with E4X.
We’re going to start by accessing tags and tag attributes. It’s pretty straight forward. In the following code, I accessed the name tag found under the first employee tag. If the name tag has no additional tags inside, then the value returned is a string.
myXML.employee[0].name
In the next code block, I’m accessing the employee tag's type attribute. To access attributes, you need to use the attribute punctuator (@). It looks a little weird, but it hey it works.
myXML.employee[0].@type
But the real nice thing about E4X isn’t that you can retrieve value, you can also set them.
myXML.employee[0].name = "David";
myXML.employee[0].@type = "Full-time";
The XML document will now have those new values. But it doesn’t stop there, you can create a new XML document from scratch. The following code will create a basic HTML page.
var newXML:XML = new XML("<html />");
newXML.head.title = "New HTML Page";
newXML.head.title.@lang = "en-US";
newXML.body = "HTML Page content goes here";
And here is what it looks like.
<html>
<head>
<title lang="en-US">New HTML Page</title>
</head>
<body>HTML Page content goes here</body>
</html>
Of course we’ve only just scratch the surface. In my next E4X post, I’ll be showing you how to work with XMLLists and further down the road namespaces.