Leonidas-from-XIV / node-xml2js

XML to JavaScript object converter.
MIT License
4.87k stars 601 forks source link

Get array to preserve order of same tag #592

Open jbdemonte opened 3 years ago

jbdemonte commented 3 years ago

Hi,

Is there a way to preserve order of children, without associating same tags

I mean, with :

import { parseStringPromise } from 'xml2js';

async function parse() {
  const xml = `
  <a>
    <b>1</b>
    <c>2</c>
    <b>3</b>
  </a>
  `;
  console.log(await parseStringPromise(xml, { preserveChildrenOrder: true }));
}

parse().catch(console.error);

I got :

{ a: { b: [ '1', '3' ], c: [ '2' ] } }

I want to preserve the order and get something like :

[
  { a: [
      { b: 1 },
      { c: 2 },
      { b: 3 },
    ]
  }
]

Is it possible?

Salketer commented 3 years ago

The preserveChildrenOrder option is there for that. You'll have all children inside an array. Each will have the #name property added so you know what is the tag.

adrianovalente commented 3 years ago

@jbdemonte it seems that this option needs to be used combined with explicitChildren: true

satyajitnayk commented 3 months ago

preserveChildrenOrder: true is not working as expected.