Node + xmldom: How to 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 am trying to do the following:

Actions

  • Read the XML file in line
  • Convert string to XML object using xmldom
  • Set the field <name>default</name>to<name>test</name>
  • Convert XML object to string

Problem

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

Code

Here is the code 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);
});

, <name> test ... , ? - , ?

!

+4
1

, !

nodeValue, data.

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

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

!

+4

Source: https://habr.com/ru/post/1609524/


All Articles