0

I'm having some trouble replacing text inside an XML node in Node.js (v0.12.0). The "nodeValue" property appears to let me read the text from the node, but not change it.

I'm using the node modules "xpath.js" (1.0.6) and "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:

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?

2

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.