tags:

views:

184

answers:

2

How can I get the order of an element attribute list? It's not totally necessary for the final processing, but it's nice to:

  • in a filter, not to gratuitously reorder the attribute list

  • while debugging, print the data in the same order as it appears in the input

Here's my current attribute processor which does a dictionary-like pass over the attributes.

class MySaxDocumentHandler(xml.sax.handler.ContentHandler):
    def startElement(self, name, attrs):
        for attrName in attrs.keys():
            ...
+1  A: 

I don't think it can be done with SAX (at least as currently supported by Python). It could be done with expat, setting the ordered_attributes attribute of the parser object to True (the attributes are then two parallel lists, one of names and one of values, in the same order as in the XML source).

Alex Martelli
+1  A: 

Unfortunately, it's impossible in the Python implementation of Sax.

This code from the Python library (v2.5) tells you all you need to know:

class AttributesImpl:

    def __init__(self, attrs):
        """Non-NS-aware implementation.
        attrs should be of the form {name : value}."""

        self._attrs = attrs

The StartElement handler is passed an object implementing the AttributeImpl specification, which uses a plain ol' Python dict type to store key/value pairs. Python dict types do not guarantee order of keys.

Triptych
http://www.python.org/dev/peps/pep-0372/ coincidentally this very thing is mentioned in PEP 372 for OrderedDict under the heading "Future Directions": "With the availability of an ordered dict in the standard library, other libraries may take advantage of that. For example, ElementTree could return odicts in the future that retain the attribute ordering of the source file."
Adam Bernier