Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!!

like image 866
Katie Avatar asked Sep 29 '15 18:09

Katie


People also ask

How do you change a value in XML?

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.

How do you write data in XML using node JS?

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.

What is node value in XML?

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.


1 Answers

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!

like image 51
Katie Avatar answered Oct 04 '22 11:10

Katie