Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a new, empty document with javascript

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?

like image 307
morgancodes Avatar asked Dec 29 '22 23:12

morgancodes


2 Answers

I hade the same issue and I solved it like below:

xmlDoc = document.implementation.createDocument("", "", null);
root = xmlDoc.createElement("description");
xmlDoc.appendChild(root);
alert((new XMLSerializer()).serializeToString(xmlDoc));
like image 78
Ralph Avatar answered Jan 01 '23 14:01

Ralph


You can create an empty document in a W3C DOM compliant browser (IE9+ and the rest) with the following code.

var doc = (new DOMParser()).parseFromString('<dummy/>', 'text/xml');
doc.removeChild(doc.documentElement);
like image 38
Angel Yordanov Avatar answered Jan 01 '23 13:01

Angel Yordanov