How can I add new node/element or update xml file in node js express? I try to do it with cheerio, my code:
$ = cheerio.load("my.xml", {xmlMode: true});
$('urlset').append('<url><loc>www.google.com</loc></url>');
You just format the whole XML file into JSON, and then add the data you want, and once is done, just format the JSON to XML
const js2xmlparser = require('js2xmlparser');
const xml2js = require('xml2js').parseString;
// Rading your XML file
const origin = '<?xml version="1.0" encoding="UTF-8"?> <root> <name>Felix</name> </root>';
// Making a JSON object so you can edit it easily
xml2js(origin, (error, editableJSON) => {
if(error){
console.log(error);
}else{
editableJSON.stackOverflow = true;
// Making it back to XML
const resultXML = js2xmlparser.parse('root', editableJSON);
console.log(resultXML)
}
});
XMLfile intoJSON, and then add the data you want, and once is done, just format theJSONback toXML?