libs icon indicating copy to clipboard operation
libs copied to clipboard

xml: Add preserverOrder option

Open eze1214 opened this issue 1 year ago • 1 comments

Imagine that I have the following XML, and the order of elements is crucial. As far as I understand, a way to handle this case does not exist. ´´´

hello world monde 42 世界 🌏 true content ´´´

It would be convenient to have an option to handle this use case. The JSON result will be more complex, but I will handle this use case appropriately.

eze1214 avatar Jan 15 '25 23:01 eze1214

It is technically already (partially) possible, though there's an open issue for that:

  • #57

In JS, dictionnaries are ordered so when the parser will build the document, it'll add them in the order it found them. For the same reason, when the stringifier iterates on the object properties, it'll add them in the order you registered

You can verify this behaviour in your browser:

Reordering objects is achievable but kind of tedious

const {foo, bar} = JSON.parse(`{"foo":1, "bar":2}`) 
JSON.stringify({bar, foo}) 

However, the mentionned issue is because when using an array element, the stringifier will iterate over it at once, effectively loosing order for this particular datatype if your elements were spread across the same node, but for the documents without array you can exploit the behaviour described above

lowlighter avatar May 30 '25 04:05 lowlighter