Using node v.0.10.29, Express v4.12.0, and xmldom v0.1.19, I'm trying to do the following:
Steps
- Read an XML file into a string
- Convert the string into an XML object using xmldom
- Set the
<name>default</name>
field to<name>test</name>
- 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!!
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!
来源:https://stackoverflow.com/questions/32850812/node-xmldom-how-do-i-change-the-value-of-a-single-xml-field-in-javascript