繁体   English   中英

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

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

我在替换Node.js(v0.12.0)中的XML节点内的文本时遇到了一些麻烦。 出现“ nodeValue”属性使我可以从节点读取文本,但不能更改它。

我正在使用节点模块“ xpath.js ”(1.0.6)和“ xmldom ”(0.1.19)

我的代码:

// 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"

我整理了一个runnable.com项目,演示了此行为:

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

谁能发现我在做什么错? 还有另一种方法可以做到这一点吗?

我找到了一种解决方法,可以为我解决此问题:

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

它看起来像是XMLDOM中的一个错误,与上游项目中的Web浏览器兼容性链接在一起(请参阅#116#33 )。

暂无
暂无

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

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