Leonidas-from-XIV / node-xml2js

XML to JavaScript object converter.
MIT License
4.88k stars 602 forks source link

Order of elements is being destroyed #499

Open philiprbrenan opened 5 years ago

philiprbrenan commented 5 years ago

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");
 });
UnbearableBear commented 5 years ago

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.

bluenote10 commented 4 years ago

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

UnbearableBear commented 4 years ago

@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

alcalyn commented 4 years ago

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.

marvinirwin commented 2 years ago

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

eMahtab commented 2 years ago

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.