0

I am trying to convert XML file into NodeJS object while keeping the same order as the original file. I have tried using the library xml2js, but it produces an object (not an array), and merges the tags with the same name.

For example the following XML :

<xml>
<a>...</a>
<b>...</b>
<a>...</a>
<c>...</c>
</xml>

results, with xml2js, in something like :

{
a : [[Object], [Object]],
b : [[Object]],
c : [[Object]],
}

'a' tags are merged, which I don't want.

What I want is something like :

[
{a : [Object]},
{b : [Object]},
{a : [Object]},
{c : [Object]}
]

thus keeping the same order as the original XML file. Do you have any idea how to achieve this ? Thanks ?

Nelibo
  • 13
  • 4
  • What you want isn’t valid JS, and objects can’t have duplicate property names. *(They can be **written** with duplicate prop names, but last one wins.)* – Dave Newton Jan 04 '23 at 13:28
  • Thanks @DaveNewton, I have just noticed it is invalid indeed, I have edited my post. – Nelibo Jan 04 '23 at 13:32
  • Does the [`xml2js` option](https://www.npmjs.com/package/xml2js#options) `preserveChildrenOrder: true` achieve what you want? – Heiko Theißen Jan 04 '23 at 13:39
  • @HeikoTheißen Yes it does ! Thank you very much. I tried it earlier but forgot to add the option explicitChildren : true along with it. – Nelibo Jan 04 '23 at 13:48

0 Answers0