Create XML in Javascript

BigBug picture BigBug · Jan 15, 2013 · Viewed 146.1k times · Source

I'm wondering, is it possible to create an XML file with some data in Javascript? I have the data stored in variables.

I've googled around a bit and it doesn't seem like it's talked about much. I thought i could use XMLWriter such as this:

var XML = new XMLWriter();
XML.BeginNode ("testing");
XML.Node("testingOne");
XML.Node("TestingTwo");
XML.Node("TestingThree");
XML.EndNode();

as stated in this tutorial:EHow Tutorial

However, when i execute this code i get the following error:

ReferenceError: XMLWriter is not defined

Any ideas on how i can get started with this?

Thanks in advance!

Answer

Seb3736 picture Seb3736 · Dec 2, 2015

Disclaimer: The following answer assumes that you are using the JavaScript environment of a web browser.

JavaScript handles XML with 'XML DOM objects'. You can obtain such an object in three ways:

1. Creating a new XML DOM object

var xmlDoc = document.implementation.createDocument(null, "books");

The first argument can contain the namespace URI of the document to be created, if the document belongs to one.

Source: https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument

2. Fetching an XML file with XMLHttpRequest

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {

    var xmlDoc = xhttp.responseXML; //important to use responseXML here
}
xhttp.open("GET", "books.xml", true);
xhttp.send();

3. Parsing a string containing serialized XML

var xmlString = "<root></root>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlString, "text/xml"); //important to use "text/xml"

When you have obtained an XML DOM object, you can use methods to manipulate it like

var node = xmlDoc.createElement("heyHo");
var elements = xmlDoc.getElementsByTagName("root");
elements[0].appendChild(node);

For a full reference, see http://www.w3schools.com/xml/dom_intro.asp

Note: It is important, that you don't use the methods provided by the document namespace, i. e.

var node = document.createElement("Item");

This will create HTML nodes instead of XML nodes and will result in a node with lower-case tag names. XML tag names are case-sensitive in contrast to HTML tag names.

You can serialize XML DOM objects like this:

var serializer = new XMLSerializer();
var xmlString = serializer.serializeToString(xmlDoc);