Monday, January 11, 2010

For Adobe AS3 XMLNS = 'XML Non Sense'

I have been playing around with Adobe Actionscript 3 & had a pretty frustating experience. My AS3 / Flex program is calling a web service & getting back an XML response. All I want to do is put this XML into Flex UI using a grid view control by culling selective nodes from the XML into an Array.

This proved to be a Herculean task & took me a few days to figure out. Now, I am certainly a newbie to Actionscript but not new to programming in general. Getting an XML response back from a web service & displaying it on UI is usually a breeze (esp. in .Net etc.).

Unfortunately, AS3 has a bug due to which it cannot parse XML with namespaces very well. As a matter of fact, it simply cannot traverse the XML tree to give you the nodes unless you have stripped it free of the namespaces. Considering that Actionscript is in its third incarnation (& considering that XML has been around for a while), this just seems unacceptable.

Here is the function / workaround that I found on this blog to strip off the namespace...

private function removeNamspaces(...rest):String
{
rest[0] = rest[0].replace(/xmlns[^"]+\"[^"]+\"/g, "");
var attrs:Array = rest[0].match(/\"[^"]*\"/g);
rest[0] = rest[0].replace(/\"[^"]*\"/g, "%attribute value%");
rest[0] = rest[0].replace(/(<\/?|\s)\w+\:/g, "$1");
while (rest[0].indexOf("%attribute value%") > 0)
{
rest[0] = rest[0].replace("%attribute value%", attrs.shift());
}
return rest[0];
}

After dealing with Adobe AS3's buggy XML parsing, MSFT sure does not look bad ;-)