Question

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():
            ...
Was it helpful?

Solution

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).

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top