Using node v.0.10.29, Express v4.12.0, and xmldom v0.1.19, I'm trying to do the following:
<name>default</name>
field to <name>test</name>
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).
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!!
The way to change the value of an attribute, is to change its text value. This can be done using the setAttribute() method or setting the nodeValue property of the attribute node.
var obj = {title: "Tony", link: "Stark" , "description":"hi"}; var fs = require('fs'); var xml2js = require('xml2js'); var builder = new xml2js. Builder(); var xml = builder. buildObject(obj); fs. writeFile('feed.
Element nodes do not have a text value. The text value of an element node is stored in a child node. This node is called a text node. To retrieve the text value of an element, you must retrieve the value of the elements' text node.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With