xmldoc
xmldoc copied to clipboard
Attribute ordering
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:
- Clean api (breaking change):
Change attr
from object to a list of {name: string, value: string}
objects.
- Redundant approach (non breaking):
Add an additional attribute attrOrder
of that is a ordered list of the attribute names.
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!
Hi @nfarina
Thanks for the fast response!
Generally you are right of course. But two cases are worth mentioning/considering:
- order is only guaranteed for ES2015
- when manipulating attributes an explicit order would make things easier
Object.entries(someXmlNode.attr).forEach((([attributeName, attrValue]), idx) => {
console.log(`${attributeName} = ${attrValue} is at index ${idx}`);
});
should work for number 2.