Home > Blockchain >  xml2js not writing as expected
xml2js not writing as expected

Time:05-12

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.

CodePudding user response:

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

CodePudding user response:

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.

  • Related