节点js将节点或元素添加到xml文件

时间:2017-08-08 13:49:32

标签: node.js xml dom cheerio

如何在节点js express中添加新节点/元素或更新xml文件? 我试着用cheerio来做,我的代码:

$ = cheerio.load("my.xml", {xmlMode: true});    
$('urlset').append('<url><loc>www.google.com</loc></url>');

1 个答案:

答案 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)
    }
});

演示 https://runkit.com/moongod101/598bd24d5a737100125cb948