1

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.

  • I also noticed subsequent updates just *append*. This is not desired. The code was working fine before I added the "Nightly" sub element, it was updating `config.VersionNumber` as expected. –  May 11 '22 at 13:38

2 Answers2

1

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

traynor
  • 5,490
  • 3
  • 13
  • 23
  • Thank you. Seems weird that this isn't the default behavior to me. "Array is created only if there is more than one" sounds a bit duh. –  May 11 '22 at 15:33
  • @THEJOATMON first thought was that it's a default parsers thing, but looks like not: https://github.com/Leonidas-from-XIV/node-xml2js/blob/1832e0b6b2de30a5e326d1cf21708cd32305a538/src/parser.coffee#L56. So I guess it depends. For example, if everything is of the same type, then there is no need for extra type check maybe.. or similar.. – traynor May 11 '22 at 15:47
0

So I fixed the issue by simply adding [0] to each element:

result.config.Nightly[0].AppName[0] = message.AppName;
result.config.Nightly[0].VersionNumber[0] = message.VersionNumber;
result.config.Nightly[0].Branch[0] = message.Branch;

I'm posting this as an answer because it fixed it, but I'd love to see other answers or explanations.