Sometimes, we want to generate an XML document in-memory with JavaScript.
In this article, we’ll look at how to generate an XML document in-memory with JavaScript.
Generate an XML Document In-Memory with JavaScript
To generate an XML document in-memory with JavaScript, we can use varioud methods built into modern browsers.
For instance, we write:
const doc = document.implementation.createDocument(null, "report", null);
const submitterElement = doc.createElement("submitter");
const nameElement = doc.createElement("name");
const name = doc.createTextNode("John Doe");
nameElement.appendChild(name);
submitterElement.appendChild(nameElement);
doc.documentElement.appendChild(submitterElement);
console.log((new XMLSerializer()).serializeToString(doc))
We create an empty XML document with the document.implementation.createDocument
method:
const doc = document.implementation.createDocument(null, "report", null);
Then we create a few nodes with the createElement
method:
const submitterElement = doc.createElement("submitter");
const nameElement = doc.createElement("name");
const name = doc.createTextNode("John Doe");
Next, we call appendChild
to append the name
text node to the name
element.
We append the nameElement
to the submitterElement
next.
And finally we append the submitterElement
to the document root with:
nameElement.appendChild(name);
submitterElement.appendChild(nameElement);
doc.documentElement.appendChild(submitterElement);
Finally, we get the string version of the XML document and log it with:
console.log((new XMLSerializer()).serializeToString(doc))
Now we get:
<report>
<submitter>
<name>John Doe</name>
</submitter>
</report>
logged into the console as a result.
Conclusion
To generate an XML document in-memory with JavaScript, we can use varioud methods built into modern browsers.