简体   繁体   English

在node.js中的XML节点中替换文本

[英]Replacing text in an XML node in node.js

I'm having some trouble replacing text inside an XML node in Node.js (v0.12.0). 我在替换Node.js(v0.12.0)中的XML节点内的文本时遇到了一些麻烦。 The "nodeValue" property appears to let me read the text from the node, but not change it. 出现“ nodeValue”属性使我可以从节点读取文本,但不能更改它。

I'm using the node modules " xpath.js " (1.0.6) and " xmldom " (0.1.19) 我正在使用节点模块“ xpath.js ”(1.0.6)和“ xmldom ”(0.1.19)

My code: 我的代码:

// Use xpath.js and xmldom to fetch the "metadata" node
var doc = new Parser().parseFromString(jobXml, 'application/xml');
var nodes = select(doc, '/job/metadata/metafield[@name="metadata"]');
var metaNode = nodes[0];

console.log(metaNode.firstChild.nodeValue); // Output is "hello"
metaNode.firstChild.nodeValue = 'world'; // Replace "hello" with "world"
console.log(metaNode.firstChild.nodeValue); // Output is now "world"

var result = new Serializer().serializeToString(doc);
console.log(result); // text has reverted to "hello"

I've put together a runnable.com project demonstrating this behaviour: 我整理了一个runnable.com项目,演示了此行为:

http://runnable.com/VWw18wFQKv46Ng_V/sean-s-sandbox-for-node-js-and-hello-world http://runnable.com/VWw18wFQKv46Ng_V/sean-s-sandbox-for-node-js-and-hello-world

Can anyone spot what I'm doing wrong? 谁能发现我在做什么错? Is there another way to achieve this? 还有另一种方法可以做到这一点吗?

I found a workaround that solved this for me: 我找到了一种解决方法,可以为我解决此问题:

function setNodeValue(doc, node, newValue) {
    while (node.firstChild) {
        node.removeChild(node.firstChild);
    }
    var newText = doc.createTextNode(newValue);
    node.appendChild(newText);
}

It looks like a bug in XMLDOM linked to Web browser compatibility in the upstream project (see #116 and #33 ). 它看起来像是XMLDOM中的一个错误,与上游项目中的Web浏览器兼容性链接在一起(请参阅#116#33 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM