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

Order of elements is being destroyed

Open philiprbrenan opened this issue 6 years ago • 6 comments

Parsing the following Xml:

"<a id='1'><b id='b1'/><c id='c1'/><b id='b2'/></a>"

yields: {"a":{"$":{"id":"1"},"b":[{"$":{"id":"b1"}},{"$":{"id":"b2"}}],"c":[{"$":{"id":"c1"}}]}}

which destroys the fact that c1 occurs before b2. Sample test file:

const parseString = require('xml2js').parseString;

const xml = "<a id='1'><b id='b1'/><c id='c1'/><b id='b2'/></a>"

parseString(xml, function (err, result)
 {process.stderr.write(JSON.stringify(result)+"\n");
 });

philiprbrenan avatar Feb 12 '19 00:02 philiprbrenan

Yeah they have no fix for that except mixing three options which are:

explicitChildren: true,
preserveChildrenOrder: true,
charsAsChildren: true

And honestly, the output is twisted as hell with all the data duplicated. I cannot afford that, I'm switching to another library.

UnbearableBear avatar Mar 01 '19 11:03 UnbearableBear

@UnbearableBear May I ask which one? I also can't seem to get order preserving roundtrips out of this lib...

bluenote10 avatar Apr 02 '20 06:04 bluenote10

@bluenote10 I use this one which works fine to me but I'm not sure it is maintained anymore https://github.com/nashwaan/xml-js

UnbearableBear avatar Apr 02 '20 07:04 UnbearableBear

Thank you for the alternative.

I tried preserveChildrenOrder: true, then explicitChildren: true, preserveChildrenOrder: true, and it was not working, I couldn't guess I need these 3 options.

I think it's not intuitive to just keep the xml content order, and yes the result is too much duplicated.

alcalyn avatar May 08 '20 21:05 alcalyn

Ran into this issue and switched to xml-js to fix.

marvinirwin avatar Jan 11 '22 03:01 marvinirwin

Faced the same issue, unfortunately there was no way to get the exact order. explicitChildren: true, preserveChildrenOrder: true, charsAsChildren: true Even if you use above three options, you will get a lot of duplicated data. I switched to https://github.com/nashwaan/xml-js that worked for my requirements. It preserves the order.

Also if your input xml is deeply nested, you might find the https://marketplace.visualstudio.com/items?itemName=nidu.copy-json-path plugin useful (I guess similar plugins are available for other IDE's as well). You can easily navigate the output JSON using this plugin. This saved a lot of time for me.

eMahtab avatar Jul 04 '22 07:07 eMahtab