Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add/modify a node in XML file using node js

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.

like image 227
bananeeek Avatar asked Jul 07 '15 21:07

bananeeek


1 Answers

Unless the files' sizes are unacceptable and you cannot read them as a whole, you can use xml2js and never work with XML.

By using it, you can read the file, convert it in an object which is far easier to manipulate, add your stuff there and then convert it back as XML and write the result again on the original file.

Looking at your example, you create a new object and append it to the the file. Instead, you should read the already existent data and modify them, then write everything back (do not append them) to the file. To do that, you have to use the Parser object from xml2js.

like image 193
skypjack Avatar answered Oct 27 '22 08:10

skypjack