Search code examples
node.jsjsonxmlxml2js

xml2js not writing as expected


Given this XML layout:

<config>
  <Nightly>
    <VersionNumber>1.10.0</VersionNumber>
  </Nightly>
</config>

And this code (based on this article):

NewVersionNumber = '1.10.1';

fs.readFile("../config.xml", "utf-8", (err, data) => {

xml2js.parseString(data, (err, result) => {
    result.config.Nightly.VersionNumber = NewVersionNumber;

    const builder = new xml2js.Builder();
    const xml = builder.buildObject(result);

    fs.writeFile('../config.xml', xml, (err) => {
        if (err) {
            throw err;
        }
    });
});

I'm getting this result:

<config>
  <Nightly>
    <VersionNumber>1.10.0</VersionNumber>
  </Nightly>
  <Nightly>1.10.1</Nightly>
</config>

What am I doing wrong? The goal is for it to update the config.Nightly.VersionNumber value.


Solution

  • try using explicitArray:false params:

    xml2js.parseString(data, {explicitArray:false}, (err, result) => {
    

    see here:

    explicitArray (default: true): Always put child nodes in an array if true; otherwise an array is created only if there is more than one.

    https://www.npmjs.com/package/xml2js#options