ProAnswers.org

ElementTree vs DOM and SAX?

Python has several ways to parse XML…

I understand the very basics of parsing with SAX. It functions as a stream parser, with an event-driven API.

I understand the DOM parser also. It reads the XML into memory and coverts it to objects that can be accessed with Python.

Generally speaking, it was easy to choose between the 2 depending on what you needed to do, memory constraints, performance, etc.

Since Python 2.5, we also have ElementTree. How does this compare to DOM and SAX? Which is it more similar to? Why is it better than the previous parsers?

ElementTree is much easier to use, because it represents an XML tree (basically) as a structure of lists, and attributes are represented as dictionaries.

ElementTree needs much less memory for XML trees than DOM (and thus is faster), and the parsing overhead via iterparse is comparable to SAX. Additionally, iterparse returns partial structures, and you can keep memory usage constant during parsing by discarding the structures as soon as you process them.



ElementTree, as in Python 2.5, has only a small feature set compared to full-blown XML libraries, but it's enough for many applications. If you need a validating parser or complete XPath support, lxml is the way to go. For a long time, it used to be quite unstable, but I haven't had any problems with it since 2.1.



ElementTree deviates from DOM, where nodes have access to their parent and siblings. Handling actual documents rather than data stores is also a bit cumbersome, because text nodes aren't treated as actual nodes. In the XML snippet.



This is a test 



The string test will be the so-called tail of element b.



In general, I recommend ElementTree as the default for all XML processing with Python, and DOM or SAX as the solutions for specific problems.