1

I know this question has been asked in the past, but they have all been dated a few years back. I am wondering if there has been any changes made to Python modules such as lxml, minidom, or etree that will allow us to preserve the attribute order in XML files without patching.

I need the order to be preserved as the program I am supplying the files to relies on it.

If there are no updates, what's the easiest way to implement this?

kjhughes
  • 106,133
  • 27
  • 181
  • 240
Polyhedronic
  • 63
  • 1
  • 1
  • 10
  • 4
    If the program you are supplying the files to depends on the order of the attributes then that program has a bug which should be fixed. – Adrian W Jul 08 '18 at 21:38
  • Unfortunately, the program is external so, I cant do much about it. And the attributes are part of subelements whose data are very relevant. – Polyhedronic Jul 09 '18 at 02:32
  • 1
    You can use `OrderedDict` to preserve attribute order with lxml. See https://stackoverflow.com/a/22596064/407651 – mzjn Jul 09 '18 at 11:59
  • In addition to the answer/comment by @mzjn : this answer might be interesting also: https://stackoverflow.com/a/54034770/960592 – Ideogram Dec 08 '21 at 12:54
  • @Ideogram: ElementTree and minidom in Python 3.8 preserve attribute order: https://stackoverflow.com/a/60176826/407651, https://stackoverflow.com/a/61267614/407651 – mzjn Dec 08 '21 at 14:08

1 Answers1

3

The insignificance of attribute ordering is not a technical limitation to be lifted in future implementations of XML libraries.

Attribute order is insignificant per the XML Recommendation:

Note that the order of attribute specifications in a start-tag or empty-element tag is not significant.

Thus, you should not base your design upon any particular ordering of attributes in XML.

In the very rare circumstances where an application absolutely must order XML attributes, see the section on attribute processing in the XML Normalization Recommendation or the Canonical XML Recommendation.

kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • consistent with how libraries deal with attributes: they return a dict. – bobrobbob Jul 08 '18 at 18:19
  • hey, thanks for the links and the answer. The program I am feeding this to is not mine, unfortunately and it is proprietary. That is exactly why I wanted to know if this is possible. I do understand that the xml protocols and how they are stored. But I just wanted to know if this option was implemented considering the fact that this has been asked several times. – Polyhedronic Jul 09 '18 at 02:31