I have an XML fragment that I parse using jQuery parseXML. Most nodes don't have prefixes, they are in the default namespace and some have a prefixes.
I need all the nodes that are in the default namespaces to be associated with a prefix instead. I've made sure that this prefix is already declared in the string version of the XML with a magical string replace (i.e. xmlns:my="http://mydefaulns.com" is declared at the root level when I load the XML.)
I tried the following:
var defaultNs="http://mydefaulns.com";
var xmlDoc = $.parseXML(stringXML);
$(xmlDoc).find("*").each(function() {
if (this.namespaceURI=== defaultNs) {
this.prefix = "my";
}
}
But it has no impact, when I write the XML back there's still no prefix.
I've also tried to just load the XML and call:
xmlDoc.firstChild.removeAttribute("xmlns")
but the attribute wasn't removed so the prefixes were not magically updated.
At that point, I think the only way to get the result that I want would be to recreate all the nodes with the new prefixed name, copying all the attributes.
This seem really extreme, is there another way?
Input (string):
<abc xmlns="http://mydefaulns.com" xmlns:my="http://mydefaulns.com"xmlns:other="http://other.com">
<node1>Value</node1>
<other:node2>Value2</other:node2>
</abc>
Desired output:
<my:abc xmlns:my="http://mydefaulns.com"xmlns:other="http://other.com">
<my:node1>Value</my:node1>
<other:node2>Value2</other:node2>
</my:abc>
The actual XML is more complex, but this gives you an idea.
I parse the XML with jQuery.parse and and get back the string version by using
function XMLDocumentToString(oXML) {
if (typeof oXML.xml != "undefined") {
return oXML.xml;
} else if (XMLSerializer) {
return (new XMLSerializer().serializeToString(oXML));
} else {
throw "Unable to serialize the XML";
}
}