1

I have a libxmljs XML object. I want to write it to a file; here is so far what I have.

var libxml = require('libxmljs');
var xml =  '<?xml version="1.0" encoding="UTF-8"?>' +
           '<root>' +
               '<child foo="bar">' +
                   '<grandchild baz="fizbuzz">'+
            '<blah>grandchild content<inblah>blah blah</inblah></blah>' +
            '<blah1>grandchild content blah2</blah1>'+
           '</grandchild>' +
               '</child>' +
             '</root>';


var xmlDoc = libxml.parseXml(xml);
//..... do some changes to xmlDoc
console.log(xmlDoc.toString()); 

I want to write xmlDoc to a separate file. Such as result.xml

Udy Warnasuriya
  • 959
  • 2
  • 12
  • 23
  • You should take a look at [this question](http://stackoverflow.com/q/2897619/589985) - the first three answers are all possible solutions. – Xavier Holt Dec 24 '12 at 15:06
  • Thanks @XavierHolt but that doesn't seem to be help. I'm using NodeJS library. So I need to find a solution which can be used in NodeJS. – Udy Warnasuriya Dec 24 '12 at 15:12
  • Whoops! Thought it was running in the browser... Try [this question](http://stackoverflow.com/q/2496710/589985) instead. – Xavier Holt Dec 24 '12 at 15:14
  • yeah. sorry I did not mention it in my question. I found a solution from your link. thank you so much @XavierHolt. – Udy Warnasuriya Dec 24 '12 at 15:59

1 Answers1

2

Use the built in fs module in node.js. Like this:

var js = require('fs');
var libxml = require('libxmljs');
var xml =  '<?xml version="1.0" encoding="UTF-8"?><root>foobar</root>';

var xmlDoc = libxml.parseXml(xml);
//..... do some changes to xmlDoc
fs.writeFile('test.xml', xmlDoc.toString(), function(err) {
  if (err) throw err;
  console.log('Wrote XML string to test.xml'); 
});

You can read further about the fs module here: http://nodejs.org/api/fs.html#fs_fs_readfile_filename_options_callback

Lilleman
  • 7,392
  • 5
  • 27
  • 36