Posted By

Activetuts on 01/13/11


Tagged


Versions (?)

Who likes this?

13 people have marked this snippet as a favorite

chus
elbjoern
toxin20
meekgeek
ichnoweb
kure69
AndrewPotter
JaaQ
im3der
elderhsouza
merritt212
coutlasssupreme
flashdeveloper


Strip XML Namespaces


 / Published in: ActionScript 3
 

URL: http://enva.to/e4ig6z

Loading XML, specifically from 3rd party sources can sometimes prove problematic when the XML makes use of namespaces. This snippet will take an XML object and strip all namespace declarations and prefixes. This snippet leaves the input XML unchanged and returns a new XML object.

  1. function stripXMLNamespaces(xml:XML):XML
  2. {
  3. var s:String = xml.toString();
  4. var pattern1:RegExp = /\s*xmlns[^\'\"]*=[\'\"][^\'\"]*[\'\"]/gi;
  5. s = s.replace(pattern1, "");
  6. var pattern2:RegExp = /<[\/]{0,1}(\w+:).*?>/i;
  7. while(pattern2.test(s)) {
  8. s = s.replace(pattern2.exec(s)[1], "");
  9. }
  10. return XML(s);
  11. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: jschadwell on September 26, 2012

This code won't work for XML elements containing attributes. For example:

The code snippet will handle strip the "ns" qualifier from "foo," but won't touch "attr1" or "attr2."

Posted By: jschadwell on September 26, 2012

Hmmm...the XML example I posted didn't come through. Let me try that again:

<ns:foo ns:attr1="bar" ns:attr2="baz">

Posted By: jschadwell on September 26, 2012

This seems to work:

function stripXMLNamespaces(xml:XML):XML { var s:String = xml.toString(); var pattern1:RegExp = /\sxmlns[^\'\"]=[\'\"][^\'\"][\'\"]/gi; s = s.replace(pattern1, ""); var pattern2:RegExp = /(<[\/]{0,1})(\w+:)(.?>)/i; while(pattern2.test(s)) { s = s.replace(pattern2, "$1$3"); } var pattern3:RegExp = /(<[\/]{0,1}.?)(\w+:)(\w+=[\'\"][^\'\"][\'\"])(.*?>)/i; while(pattern3.test(s)) { s = s.replace(pattern3, "$1$3$4"); } return XML(s); }

Posted By: jschadwell on September 26, 2012

Or with newlines:

function stripXMLNamespaces(xml:XML):XML { var s:String = xml.toString(); var pattern1:RegExp = /\sxmlns[^\'\"]=[\'\"][^\'\"][\'\"]/gi; s = s.replace(pattern1, ""); var pattern2:RegExp = /()/i; while(pattern2.test(s)) { s = s.replace(pattern2, "$1$3"); } var pattern3:RegExp = /()/i; while(pattern3.test(s)) { s = s.replace(pattern3, "$1$3$4"); } return XML(s); }

Posted By: jschadwell on September 26, 2012

One more try:

function stripXMLNamespaces(xml:XML):XML {
var s:String = xml.toString();
var pattern1:RegExp = /\sxmlns[^\'\"]=[\'\"][^\'\"][\'\"]/gi;
s = s.replace(pattern1, "");
var pattern2:RegExp = /()/i;
while(pattern2.test(s)) {
s = s.replace(pattern2, "$1$3");
}
var pattern3:RegExp = /()/i;
while(pattern3.test(s)) {
s = s.replace(pattern3, "$1$3$4");
}
return XML(s);
}

Posted By: jschadwell on September 26, 2012

Closer, but you'll have to fix the indenting.

You need to login to post a comment.