节点js将节点或元素添加到xml文件 [英] node js adding node or element to xml file

查看:153
本文介绍了节点js将节点或元素添加到xml文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>');


推荐答案

您只需将整个XML文件格式化为JSON,然后然后添加所需的数据,并完成操作,只需将JSON格式化为XML

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

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

这篇关于节点js将节点或元素添加到xml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆