Leonidas-from-XIV / node-xml2js

XML to JavaScript object converter.
MIT License
4.84k stars 598 forks source link

Enable setting attributes when building obj with array #625

Open jansule opened 2 years ago

jansule commented 2 years ago

This solves #624

This allows setting attributes on parent elements, while preserving the order of its children, when using builder.buildObject().

I know this is some rather hakish code, as we are setting properties on an array, but I don't see any other way of providing this functionality. Please let me know, if we should follow a different approach here.

Example:

let children = [{Literal: 'foo'}, {PropertyName: 'bar'}, {Literal: 'baz'}];
children.$ = {name: 'faz'};
builder.buildObject({Parent: [children]});

leads to following result:

<Parent name="faz">
  <Literal>foo<Literal>
  <PropertyName>bar</PropertyName>
  <Literal>baz<Literal>
</Parent>