javascript - How to add/modify a node in XML file using node js -
let's have 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 want add new node, let's following:
<person> <name>tony</name> <surname>stark</surname> </person> how do in node js? mean have file (/routes/index.js in node js express, exact), , want able add/modify existing xml file. i've tried fs.writefile(), writes whole new file, , fs.appendfile() adds header(?xml + encoding , stuff) , root nodes after last node, can't insert catalog node. can't rid of xml declaration header either.
i've been using .builder() this, , looked
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 want data from addnode, won't create var obj in function.
unless files' sizes unacceptable , cannot read them whole, can use xml2js , never work xml.
by using it, can read file, convert in object far easier manipulate, add stuff there , convert xml , write result again on original file.
looking @ example, create new object , append the file. instead, should read existent data , modify them, write (do not append them) file. that, have use parser object xml2js.
Comments
Post a Comment