DOM Parser vs SAX Parser
Estimated study time: 20 minutes.
The two classic approaches to XML parsing — DOM and SAX — take fundamentally different strategies, each with real trade-offs.
DOM (Document Object Model) Parser
Loads the entire XML document into memory as a tree structure, which you can then freely navigate, search, and modify in any order.
import xml.dom.minidom as minidom
doc = minidom.parse('course.xml')
titles = doc.getElementsByTagName('title')
print(titles[0].firstChild.data)
SAX (Simple API for XML) Parser
Reads the document sequentially from start to end, firing events (start tag, end tag, text) as it goes — without ever holding the whole document in memory.
import xml.sax
class CourseHandler(xml.sax.ContentHandler):
def startElement(self, name, attrs):
print("Start:", name)
def endElement(self, name):
print("End:", name)
xml.sax.parse('course.xml', CourseHandler())
Key Differences
- Memory usage — DOM loads everything at once (higher memory); SAX processes a stream (very low memory).
- Navigation — DOM allows random, repeated access to any part of the tree; SAX is forward-only, one pass.
- Modification — DOM lets you edit and rewrite the document; SAX is read-only by nature.
- Speed on large files — SAX is typically faster and more scalable for very large documents.
When to Use Which
- Use DOM for small-to-medium files where you need to navigate back and forth or edit the document.
- Use SAX for large files where memory efficiency matters more than convenience.
💡 Tip: If you find yourself needing SAX's memory efficiency but also want easier, cursor-style code, look at StAX as a middle ground between the two.