Namespaces on Attributes with E4X in ActionScript 3

I recently came accross an odd behavior when adding namespaces to an attrubute using E4X. I needed to create an XML object like the following:

1
<body xml:lang="en" xmpp:version="1.0" xmlns:xml="http://www.w3.org/XML/1998/namespace" xmlns:xmpp="urn:xmpp:xbosh" />

This XML element is created dynamically within the ActionScript code like this:

1
2
3
4
5
var body:XML = <body />;
var xml:Namespace = new Namespace("xml", "http://www.w3.org/XML/1998/namespace");
body.@xml::lang = "en";
var xmpp:Namespace = new Namespace("xmpp", "urn:xmpp:xbosh");
body.@xmpp::version = "1.0";

However, the output of the namespaces in the XML was off:

1
<body aaa:lang="en" aab:version="1.0" xmlns:aaa="http://www.w3.org/XML/1998/namespace" xmlns:aab="urn:xmpp:xbosh" />

I realize this is still valid, but the server was having issues with it. That’s when I discovered that I need to first add the namespaces to the XML element using addNamespace(). This then gave me the right output:

1
2
3
4
5
6
7
var body:XML = <body />;
var xml:Namespace = new Namespace("xml", "http://www.w3.org/XML/1998/namespace");
body.addNamespace(xml);
body.@xml::lang = "en";
var xmpp:Namespace = new Namespace("xmpp", "urn:xmpp:xbosh");
body.addNamespace(xmpp);
body.@xmpp::version = "1.0";

Hopefully this will save someone else an hour of banging his or her head against the wall.