Libraries to write xml with JavaScript

Karussell picture Karussell · Oct 31, 2010 · Viewed 19.3k times · Source

I am doing some server side coding with JavaScript (node.js) and I would like to write valid xml.

I found two libs, but I am sure there are more/better!?

Requirements: open source (for commercial usage)

Would be cool if the project is fast, small and simple to use (in that order). And I would like to have a bit lower level access ala

doc.addElement('xy').addAttr('name', 'bob');

Answer

Wahid Kadwaikar picture Wahid Kadwaikar · Jul 15, 2014

I've created two functions as follows:

function loadXMLDoc(filename){
  if (window.XMLHttpRequest){
      xhttp=new XMLHttpRequest();
  }
  else {
  xhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE 5-6
  }
  xhttp.open("GET",filename,false);
  xhttp.send();
  return xhttp.responseXML;
}

And, to write the XML into a local file call the following function.

function writeXML() 
    {
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        var fso = new ActiveXObject("Scripting.FileSystemObject");
        var FILENAME="D:/YourXMLName/xml";
        var file = fso.CreateTextFile(FILENAME, true);
        file.WriteLine('<?xml version="1.0" encoding="utf-8"?>\n');
        file.WriteLine('<PersonInfo>\n');
        file.WriteLine('></Person>\n');
        } 
        file.WriteLine('</PersonInfo>\n');
        file.Close();
    } 

I hope this helps, or else you can try Ariel Flesler's XMLWriter for creating XML in memory.