node-xml2js icon indicating copy to clipboard operation
node-xml2js copied to clipboard

Get array to preserve order of same tag

Open jbdemonte opened this issue 4 years ago • 3 comments

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?

jbdemonte avatar Nov 18 '20 17:11 jbdemonte

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.

Salketer avatar Jan 19 '21 08:01 Salketer

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

adrianovalente avatar Apr 10 '21 00:04 adrianovalente