Let's say I have the following xml code
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<catalog>
<person>
<name>John</name>
<surname>Smith</surname>
</person>
<person>
<name>Abe</name>
<surname>Lincoln</surname>
</person>
<person>
<name>James</name>
<surname>Bond</surname>
</person>
</catalog>
And I want to add a new node, let's say the following:
<person>
<name>Tony</name>
<surname>Stark</surname>
</person>
How do I do this in node js? I mean I have a file (/routes/index.js in node js express, to be exact), and I want to be able to add/modify existing xml file. I've tried fs.writeFile(), but this writes a whole new file, and fs.appendFile() adds a header(?xml + encoding and stuff) and root nodes after the last node, so I can't insert it into the catalog node. I can't get rid of the xml declaration header either.
I've been using .builder() to do this, and it looked like this
router.post('/addnode', function (req, res) {
var obj = {name: "Tony", surname: "Stark"};
var fs = require('fs');
var xml2js = require('xml2js');
var builder = new xml2js.Builder();
var xml = builder.buildObject(obj);
fs.writeFile('public/test.xml', xml, function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
});
Finally I want to get that data from a from addnode, so I won't create a var obj in this function.