修改“NodeJS"上的XML标签 [英] Modify XML tags on "NodeJS"

查看:31
本文介绍了修改“NodeJS"上的XML标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道如何使用 NodeJS 修改 XML 文件的标签值

Does anyone know how to modify a tag value of an XML file using NodeJS

这是我的 XML 文件:

this is my XML file:

<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
</note>

我想把改成

我在 Windows 上运行 nodeJS.到目前为止,我有以下代码;

I'm running nodeJS on windows. SO far I have following code;

var parser = new xml2js.Parser();
function xmltxt(response, postData){
    fs.readFile( './foo.xml', function(err, data) {
        parser.parseString(data, function (err, result) {
            console.dir(result.note.to[0]);
        });
    });
}

这会读取节点值,但我需要修改标签值.请帮忙.

This reads the node value but I need to modify the tag value. Please help.

推荐答案

使用 damn-simple-xml 您可以执行以下操作:

Using damn-simple-xml you can do the following:

var Serializer = require("damn-simple-xml");  // constructor
var dsx = new Serializer();
var fs = require("fs");

var out = fs.createWriteStream("./foo2.xml");

dsx.deserialize(fs.createReadStream("./foo.xml"), function(err, root) {
    if (err) {
        console.log(err);
        return;
    }
    dsx.serialize({
        name: "n",
        data: root.data
    }, 
    function(err, xmlpart, level) {
        if (err) {
            console.log(err);
            return;
        }
        out.write(xmlpart);
        if (level === 0) { // XML streaming done
            out.end(); // closes the stream.
        }
    });
});

在前面的示例中,我们在反序列化回调中收到一个 root 对象.该对象由 root.name(即根节点的名称)和 root.data 组成,后者是来自反序列化 XML 文档的实际数据.

In the previous example, we receive a root object in the deserialization callback. This object consist of root.name (i.e. the name of the root node) and root.data which is the actual data from the deserialized XML document.

然后在序列化时,我们返回相同的 root.data 对象,但在那里我们将根节点的名称更改为您的问题中指定的n".

Then when serializing, we give back the same root.data object but there we change the root node's name to "n" as specified in your question.

由于该死的简单 xml 可以使用流来输入 xml 并将其内容作为 XML 块输出,因此该库的内存占用非常小.

Since damn-simple-xml can use streams to input xml and outputs it's content as XML chunks, the library have a very small memory footprint.

这篇关于修改“NodeJS"上的XML标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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