1

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?

2 Answers2

0

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>
 */
traynor
  • 5,490
  • 3
  • 13
  • 23
0

Built the xml using xmlbuilder2.

const { create } = require('xmlbuilder2');
const orderDetails = create().ele('orderdetails');

const productsEl = orderDetails.ele('products');
products.forEach((prod: Product) => {
  const artnr = productsEl.ele('artnr');
  artnr.txt(prod.artnr).up();
});
const xml = orderDetails.end({ prettyPrint: true });
console.log(xml);

This generated the output

<?xml version="1.0"?>
 <orderdetails>
  <products>
   <artnr>05633310000</artnr>
   <artnr>05633310001</artnr>
  </products>
 </orderdetails>