I'm working with some very unintuitive xml (all the tags are things like "TX", "H", "VC").
I'd like to make a copy of this data, but with all of the tags renamed to what they actually mean. Can I create a new, empty document to put my new, nicely named tags in to?
I've tried this:
doc = (new DOMParser()).parseFromString("", 'text/xml');
but when I do so, I wind up with a document that has a child node, rather than being empty. Furthermore, that child's tagname is "parsererror"
So, any ideas how I can create an empty document?
I hade the same issue and I solved it like below:
You can create an empty document in a W3C DOM compliant browser (IE9+ and the rest) with the following code.
I don't think you can create a document without the root node. You could create a fake node:
However, a better solution might be to create constants for the node names:
The WHATWG's specification of the
createDocument
method allows one to providenull
for each of the 3 arguments tocreateDocument
, to have an "empty" XML document created and returned -- one without any root node and with theapplication/xml
as its content type.When the
document
object is available (a compliant Web user agent), the implementation with thecreateDocument
method can be referred to withdocument.implementation
:You may then trivially attach a root node of your choosing to it by simply appending it as you otherwise would, as follows (
empty_doc
would refer to the document created and returned by the call above):