Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Attribute ordering #63

Open
daniel-sc opened this issue Mar 15, 2021 · 3 comments
Open

Attribute ordering #63

daniel-sc opened this issue Mar 15, 2021 · 3 comments

Comments

@daniel-sc
Copy link

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.

@nfarina
Copy link
Owner

nfarina commented Mar 15, 2021

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!

@daniel-sc
Copy link
Author

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

@AgentEnder
Copy link

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

should work for number 2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants