Katie
Katie

Reputation: 48198

Node + xmldom: How do I change the value of a single XML field in javascript?

Using node v.0.10.29, Express v4.12.0, and xmldom v0.1.19, I'm trying to do the following:

Steps

  1. Read an XML file into a string
  2. Convert the string into an XML object using xmldom
  3. Set the <name>default</name> field to <name>test</name>
  4. Convert the XML object back into a string

Problem

The problem is that after I set the <name> field, it sets correctly in the object, but when I convert it to a string, the <name> field is back to being the old value (wrong).

Code

Here's what the code looks like for this:

var fs = require('fs');
var DOMParser = require('xmldom').DOMParser;
var XMLSerializer = require('xmldom').XMLSerializer;
var filename = "myFile.xml";

fs.readFile(filename, "utf-8", function (err,data) 
{
    //CREATE/PARSE XML OBJECT FROM STRING
    var customerConfig = new DOMParser().parseFromString(data);

    //SET VALUE TO "TEST" (<name>default</name> TO <name>test</name>)
    customerConfig.getElementsByTagName("name")[0].childNodes[0].nodeValue = "test";

    //THIS OUTPUTS "test" WHICH IS CORRECT - 
    console.log(customerConfig.getElementsByTagName("name")[0].childNodes[0].nodeValue);

    //SERIALIZE TO STRING
    var xmlString = new XMLSerializer().serializeToString(customerConfig);

    //THIS OUTPUTS THE FULL XML FILE, 
    //BUT STILL SHOWS <name>default</name> AND NOT <name>test</name>
    console.log(xmlString);
});

The problem is that the <name> field isn't setting to test in the string... I'm thinking there is a problem with the serialization part? Anyone see what I'm doing wrong?

Thank you!!

Upvotes: 7

Views: 6114

Answers (1)

Katie
Katie

Reputation: 48198

Well I figured out the problem!

I was setting nodeValue but I really needed to set data. So I changed

customerConfig.getElementsByTagName("name")[0].childNodes[0].nodeValue = "test";

to

customerConfig.getElementsByTagName("name")[0].childNodes[0].data= "test";

then it worked!

Upvotes: 11

Related Questions