3

I have just started exploring Node.js as I am planning to work on a project very soon using Node.js. I prefer saving my project data in XML file as so was looking for modules or libraries for Node.js which facilitate saving, editing, retrieving and transforming XML data. While researching on this I came across modules like xml2js, xmlbuilder, sax, node-xml and data2XML for Node.js, but none of them allows storing modified XML back to the XML file.

We use $xml->asXML("file.xml") to save an XML file in PHP and I'm looking for an alternative for this in Node.js.

hakre
  • 193,403
  • 52
  • 435
  • 836
Sameeksha Kumari
  • 1,158
  • 2
  • 16
  • 21

1 Answers1

4

DOM implementations like XMLDOM have an XMLSerializer class (Most browsers have, too). This is part of the DOM API standard.

It allows to serialize a DOM document/node into an string. You can use the fs module to save the string in a file.

var fs = require('fs');
var serializer = new (require('xmldom')).XMLSerializer;
var implementation = new (require('xmldom')).DOMImplementation;

var document = implementation.createDocument('', '', null);
document.appendChild(document.createElement('foo'));

fs.writeFile(
  "/tmp/test.xml", 
  serializer.serializeToString(document), 
  function(error) {
    if (error) {
      console.log(error);
    } else {
      console.log("The file was saved!");
    }
  }
); 
ThW
  • 19,120
  • 3
  • 22
  • 44