Search code examples
pythonxmlsax

How to parse XML with xml.sax and why it's not working


I have a piece of code whitch in my opinion should work:

#!/usr/bin/env python3

import xml.sax
import xml.sax.handler

class MyClass:
    def load_from_file(self, filename):
        class MyXmlHandler(xml.sax.handler.ContentHandler):
            def start_element(self, name, attrs):
                print('It\'s working!!!')

        xml.sax.parse(filename, MyXmlHandler())

app = MyClass()
app.load_from_file('/home/bps/Desktop/test.xml')

I'm sure that xml file is not empty, it contains many tags, but script ends silently, there is no printed strings, no error, no exception, no nothing :P Why? I'm missing something?


Solution

  • The method name should be startElement (rather than start_element), or startElementNS if your XML uses namespaces.