node.jsxml2js

xml2js building xml with one element being an array of objects


I am having an issue creating an array in XML where the array is one of elements rather than primatives.

The expected XML is:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<orderdetails>
 .....
<products>
 <artnr>05633310000</artnr>
 <artnr>05633310000</artnr>
</products>
</orderdetails>

The incorrect XML produced is:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<orderdetails>
<products>
 <artnr>05633310000</artnr>
</products>
<products>
 <artnr>05633310000</artnr>
</products>

I have tried explicitArray: true but this does not help.

Could you assist in how to get 1 products element with multiple artnr entries?


Solution

  • To achieve the result you want, you'll need to modify your input data, i.e. group objects by property, which will have as a value an array of values of that property of other objects.

    Here's an example:

    const xml2js = require('xml2js');
    const data = {
        orderdetails: {
            products: [{
                artnr: '05633310000'
            }, {
                artnr: '05633310000'
            }]
        }
    };
    
    // create a copy
    const clone = JSON.parse(JSON.stringify(data));
    
    // get object property values as an array
    clone.orderdetails.products = {
        artnr: clone.orderdetails.products.map(({
            artnr
        }) => artnr)
    };
    
    console.log(clone);
    /*
    {
        "orderdetails": {
            "products": {
                "artnr": ["05633310000", "05633310000"]
            }
        }
    }
     */
    
    const builder = new xml2js.Builder();
    const xml = builder.buildObject(clone);
    
    console.log(xml);
    
    /*
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <orderdetails>
      <products>
        <artnr>778932224</artnr>
        <artnr>778932224</artnr>
      </products>
    </orderdetails>
     */