How NOT to Code - Example 7

Jan 21, 2010

Ok, today's example is a Flex/AS3 one. Basically, when you deal with xml documents with namespaces it can be painful to search through the document. In this example, the person is stripping out the namespace info with regex before converting to an xml list to handle the data. What went wrong here?

public function result(response:Object):void
var xmlString:String;
var xmlnsPattern:RegExp;
var namespaceRemovedXML:String;
var responseXML:XML;

// get the XML payload
if(ResultEvent(response).result is XMLList)
response = ResultEvent(response).result as XMLList;
response = ResultEvent(response).result as XML;

// convert it to a string
xmlString = response.toXMLString();

// define the regex pattern to remove the namespaces from the string
xmlnsPattern = new RegExp("xmlns[^\"]*\"[^\"]*\"", "gi");

// remove the namespaces from the string representation of the XML
namespaceRemovedXML = xmlString.replace(xmlnsPattern, "");

// set the string rep. of the XML back to real XML
responseXML = new XML(namespaceRemovedXML);

// do something with the XML


John Mason

John Mason wrote on 01/28/105:56 PM

Surprised no one answered this one yet. This kind of solution drive me nuts, and you see these things on sites like Experts Exchange all the time. Their solution of stripping the namespace works but it should feel really goofy to do, and it is ;) AS3 provides a very simple solution. Simply grab the namespace with the namespace() function, then use that with your search. The following is a simple example that many people use on the AIR side to get the version from the AIR descriptor XML file, which naturally has a namespace. This is just a case of not knowing the language very well and rolling out a bad solution.

For example...
var appXML:XML = NativeApplication.nativeApplication.applicationDescriptor;
var ns:Namespace = appXML.namespace();
currentVersion = appXML.ns::version;

Write your comment

(it will not be displayed)