Skip to content

Instantly share code, notes, and snippets.

@Phrogz
Created November 19, 2018 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Phrogz/50274eb18c4cf8ca92c9e511bd280ff3 to your computer and use it in GitHub Desktop.
Save Phrogz/50274eb18c4cf8ca92c9e511bd280ff3 to your computer and use it in GitHub Desktop.
Serializing a DOM with an attribute created in an existing namespace
doc = (new DOMParser).parseFromString('<r xmlns="uri1" xmlns:xx="uri2"><b/></r>', 'text/xml');
doc.querySelector('b').setAttributeNS('uri2', 'foo', 'bar');
(new XMLSerializer).serializeToString(doc);
// "<r xmlns="uri1" xmlns:xx="uri2"><b xmlns:ns14641696="uri2" ns14641696:foo="bar"/></r>"
doc = (new DOMParser).parseFromString('<r xmlns="uri1" xmlns:xx="uri2"><b/></r>', 'text/xml');
doc.querySelector('b').setAttributeNS('uri2', 'xx:foo', 'bar');
(new XMLSerializer).serializeToString(doc);
// "<r xmlns="uri1" xmlns:xx="uri2"><b xx:foo="bar"/></r>"
doc.querySelector('b').setAttributeNS('uri2', 'foo2', 'bar2');
(new XMLSerializer).serializeToString(doc);
// "<r xmlns="uri1" xmlns:xx="uri2"><b xx:foo="bar" xmlns:ns14641696="uri2" ns14641696:foo2="bar2"/></r>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment