xmldoc icon indicating copy to clipboard operation
xmldoc copied to clipboard

Attribute ordering

Open daniel-sc opened this issue 3 years ago • 3 comments

First I'd like to mention that this lib does a great job at parsing XML without loosing und such as white space, comments etc!

It would be great if the order of the attributes could be preserved.

For this, I see two possibilities:

  1. Clean api (breaking change):

Change attr from object to a list of {name: string, value: string} objects.

  1. Redundant approach (non breaking):

Add an additional attribute attrOrder of that is a ordered list of the attribute names.

daniel-sc avatar Mar 15 '21 07:03 daniel-sc

I believe attributes are already ordered? JavaScript has a strange but handy feature where it preserves insertion order of keys on "objects". Since attributes are added to the attr object by sax in the order they were parsed, this order should be preserved.

If you use iterators like for…in or for…of on the attr object, you should get results in the expected order. Same with utility methods like Object.keys() or Object.entries().

Order should also be preserved when going back to XML via toString().

Let me know if I'm missing something though!

nfarina avatar Mar 15 '21 07:03 nfarina

Hi @nfarina

Thanks for the fast response!

Generally you are right of course. But two cases are worth mentioning/considering:

  1. order is only guaranteed for ES2015
  2. when manipulating attributes an explicit order would make things easier

daniel-sc avatar Mar 15 '21 08:03 daniel-sc

Object.entries(someXmlNode.attr).forEach((([attributeName, attrValue]), idx) => {
    console.log(`${attributeName} = ${attrValue} is at index ${idx}`);
});

should work for number 2.

AgentEnder avatar Apr 16 '21 19:04 AgentEnder