oozcitak / xmlbuilder-js

An XML builder for node.js
MIT License
918 stars 107 forks source link

Duplicate Keys In The Same Object #231

Closed fuzunspm closed 4 years ago

fuzunspm commented 4 years ago

I'm trying to add multiple keys in a single key.

Example:

<TRANSACTIONS>
    <TRANSACTION>
    </TRANSACTION>
    <TRANSACTION>
    </TRANSACTION>
</TRANSACTIONS>

..and I'm inserting with this code:

Below code is in a loop

const tempObj = {
  TRANSACTION: {
    TYPE: 0,
    MASTER_CODE: item.productCode,
    QUANTITY: item.receivedQuantity,
    UNIT_CODE: item.unit.label,
    DETAILS: `${item.requestId}: ${req.body.description}`
  }
}

temps.push(tempObj);

And then: 

obj.TRANSACTIONS = temps;
const xml = builder.create(obj).end({ pretty: true });

But this outputs like this:

<TRANSACTIONS>
    <TRANSACTION>
    </TRANSACTION>
</TRANSACTIONS>
<TRANSACTIONS>
    <TRANSACTION>
    </TRANSACTION>
</TRANSACTIONS>
oozcitak commented 4 years ago

You need to change the temp object to:

const tempObj = {
    TYPE: 0,
    MASTER_CODE: item.productCode,
    QUANTITY: item.receivedQuantity,
    UNIT_CODE: item.unit.label,
    DETAILS: `${item.requestId}: ${req.body.description}`
}

and instead insert the TRANSACTION key to the top level object:

obj.TRANSACTIONS = {
  TRANSACTION: temps
}

If the object value is an array, xmlbuilder creates an element for each item of the array. The name of each element will be the object key associated with the array. More info here: https://github.com/oozcitak/xmlbuilder-js/wiki/Conversion-From-Object#arrays

fuzunspm commented 4 years ago

Thank you very much!