如何在节点js express中添加新节点/元素或更新xml文件? 我试着用cheerio来做,我的代码:
$ = cheerio.load("my.xml", {xmlMode: true});
$('urlset').append('<url><loc>www.google.com</loc></url>');
答案 0 :(得分:1)
您只需将整个XML文件格式化为JSON,然后添加所需的数据,一旦完成,只需将JSON格式化为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)
}
});