Python XML parsing comparison of files
Question: I have to compare two XML files using Python. Each has a list of items and I
have to output which items do not appear in both. Each item has various
properties which need to agree to see if it's the same item.

Which parser would be the most suitable. It has to already be included in
Python 2.7. I looked at etree but does it enable me to do what I want easily?
Or is there something else that would be more suitable. Thanks!


Answer: it depends, if your xml element have sub element, and that sub element also
need to be compared, use DOM,

your elements to be compared only has attributes, thant using SAX is best way,
I post some SAX code here you can ref:

    
    
    import xml.sax
    from xml.sax.handler import ContentHandler
    
    class TableHandler(ContentHandler):
        def __init__(self):
            self.columns = {}
    
        def startElement(self, name, attrs):
            if name == 'R':
                for k, v in attrs.items():
                    if not self.columns.has_key(k):
                        self.columns[k] = []
                    self.columns[k].append(v)
    
    def xml_to_table(xml_str):
        handler = TableHandler()
        xml.sax.parseString(xml_str, handler)
        return handler.columns
    
    if __name__ == '__main__':    
        txt = """<xml>
        <R CatalogId="8"/><R CatalogId="8"/><R CatalogId="7"/>
        </xml>
        """
    
        columns = xml_to_table(txt)
        print columns
    

