Avoid duplicating namespaces during xml serialization using javascript -
the following code
var ns1 = 'hello:world1', doc = document.implementation.createdocument('nsdoc', 'doc', null), outer = doc.createelement('outer'), s = new xmlserializer(), elm; outer.setattribute('xmlns:ns1', ns1); elm = doc.createelementns(ns1, 'inner'); outer.appendchild(elm); console.log(s.serializetostring(outer));
outputs following xml document in chrome , firefox.
<outer xmlns:ns1="hello:world1"> <inner xmlns="hello:world1"/> </outer>
while technically still valid, there way remove duplicate ns declaration or there better api using setup namespaces on parent node use in children? eg, preferred document follows:
<outer xmlns:ns1="hello:world1"> <ns1:inner/> </outer>
figured out how gain better control on how namespaces serialized via use of domparser , little bit of uncomfortable handwritten xml (but root nodes). following javascript did this:
var parser = new domparser(), s = new xmlserializer(), dom1 = parser.parsefromstring('<doc xmlns="one"></doc>', 'text/xml'), dom2 = parser.parsefromstring('<outer xmlns="one" xmlns:ns3="hello-world"></outer>', 'text/xml'), myelm = dom2.createelementns('hello-world', 'ns3:inner'); dom2.documentelement.appendchild(myelm); dom2.documentelement.attributes.removenameditem('xmlns'); dom1.documentelement.appendchild(dom2.documentelement); console.log(s.serializetostring(dom1));
this outputs following xml in chrome (26.0 on mac), firefox (21.0 on mac) , opera (12.15 on mac -- though opera includes xml declaration ok needs)
<doc xmlns="one"> <outer xmlns:ns3="hello-world"> <ns3:inner/> </outer> </doc>
Comments
Post a Comment