ZetCode

Python XML SAX

last modified November 29, 2026 Python 3.15

In this article we show how to parse XML documents with the xml.sax module.

SAX (Simple API for XML) is an event-driven interface. The parser reads the document from start to end and reports what it finds, such as the start of an element, a piece of text, or the end of an element, by calling the methods of a handler object. It builds no tree in memory. A SAX program therefore uses little memory even for very large files, but it sees each part of the document only once and must keep any context it needs on its own.

The xml.sax module is part of the standard library and uses the Expat parser. For documents that fit in memory, the tree-based ElementTree API is usually more convenient.

Parsing events

A handler is a subclass of xml.sax.ContentHandler. We override the methods for the events we want to receive. The parseString function parses a document held in a string.

events.py
import xml.sax

data = "<shelf><book>Dune</book><book>Emma</book></shelf>"


class EventPrinter(xml.sax.ContentHandler):

    def startElement(self, name, attrs):
        print("start", name)

    def endElement(self, name):
        print("end", name)

    def characters(self, content):
        print("text", repr(content))


xml.sax.parseString(data, EventPrinter())

The startElement method receives the element name and its attributes, endElement receives the name, and characters receives text. The output shows the order in which the parser reports the events while reading the document.

$ python events.py
start shelf
start book
text 'Dune'
end book
start book
text 'Emma'
end book
end shelf

Text arrives in chunks

The parser may split the text of an element into several calls of characters, for example around entity references or at the boundaries of its input buffer. The whitespace between elements is reported as text as well. A handler should collect the pieces and use them when the element ends.

text_chunks.py
import xml.sax

data = """<shelf>
    <book>Dune</book>
    <book>Pride &amp; Prejudice</book>
</shelf>"""


class ChunkPrinter(xml.sax.ContentHandler):

    def characters(self, content):
        print(repr(content))


class TitleCollector(xml.sax.ContentHandler):

    def __init__(self):
        super().__init__()
        self.text = []
        self.titles = []

    def startElement(self, name, attrs):
        self.text = []

    def characters(self, content):
        self.text.append(content)

    def endElement(self, name):
        if name == "book":
            self.titles.append("".join(self.text))


xml.sax.parseString(data, ChunkPrinter())

collector = TitleCollector()
xml.sax.parseString(data, collector)
print(collector.titles)

The first handler shows the raw calls: line breaks and indentation come as separate pieces, and the title with &amp; arrives in three. The second handler starts a new list of pieces for every element, appends the text as it comes, and joins it in endElement. This pattern is used in all the following examples.

$ python text_chunks.py
'\n'
'    '
'Dune'
'\n'
'    '
'Pride '
'&'
' Prejudice'
'\n'
['Dune', 'Pride & Prejudice']

Attributes

The attrs argument of startElement is an Attributes object that behaves like a read-only dictionary. Attribute values are always strings.

attributes.py
import xml.sax

data = """<shelf>
    <book id="1" lang="en" pages="412">Dune</book>
    <book id="2" lang="en">Emma</book>
    <book id="3" lang="sk" pages="196">Maryša</book>
</shelf>"""


class AttrPrinter(xml.sax.ContentHandler):

    def startElement(self, name, attrs):
        if name != "book":
            return
        print(dict(attrs))
        pages = int(attrs.get("pages", 0))
        print(f"  id={attrs['id']}, names={attrs.getNames()}, pages={pages}")


xml.sax.parseString(data, AttrPrinter())

The object can be converted to a dictionary, indexed by name, and queried with get, which returns a default for missing attributes. The getNames method lists the attribute names. The page count is converted to an integer explicitly.

$ python attributes.py
{'id': '1', 'lang': 'en', 'pages': '412'}
  id=1, names=['id', 'lang', 'pages'], pages=412
{'id': '2', 'lang': 'en'}
  id=2, names=['id', 'lang'], pages=0
{'id': '3', 'lang': 'sk', 'pages': '196'}
  id=3, names=['id', 'lang', 'pages'], pages=196

Collecting records from a file

A typical SAX program turns repeated elements into records. We parse a file with products.

products.xml
<?xml version="1.0" encoding="UTF-8"?>
<products>
    <product id="1" category="tools">
        <name>Hammer</name>
        <price>12.90</price>
        <stock>35</stock>
    </product>
    <product id="2" category="garden">
        <name>Rake</name>
        <price>18.50</price>
        <stock>12</stock>
    </product>
    <product id="3" category="tools">
        <name>Screwdriver set</name>
        <price>24.00</price>
        <stock>0</stock>
    </product>
    <product id="4" category="garden">
        <name>Watering can</name>
        <price>9.99</price>
        <stock>48</stock>
    </product>
</products>

Each product has an identifier and a category as attributes and three child elements.

records.py
import xml.sax


class ProductHandler(xml.sax.ContentHandler):

    def __init__(self):
        super().__init__()
        self.products = []
        self.current = None
        self.text = []

    def startElement(self, name, attrs):
        self.text = []
        if name == "product":
            self.current = {"id": int(attrs["id"]),
                            "category": attrs["category"]}

    def characters(self, content):
        self.text.append(content)

    def endElement(self, name):
        value = "".join(self.text).strip()
        if name == "name":
            self.current["name"] = value
        elif name == "price":
            self.current["price"] = float(value)
        elif name == "stock":
            self.current["stock"] = int(value)
        elif name == "product":
            self.products.append(self.current)


handler = ProductHandler()
xml.sax.parse("products.xml", handler)

for p in handler.products:
    print(p)

The parse function accepts a file name or a file object. A new dictionary is started at each product element, the child elements fill it with converted values, and the end of the product element appends the finished record to the list.

$ python records.py
{'id': 1, 'category': 'tools', 'name': 'Hammer', 'price': 12.9, 'stock': 35}
{'id': 2, 'category': 'garden', 'name': 'Rake', 'price': 18.5, 'stock': 12}
{'id': 3, 'category': 'tools', 'name': 'Screwdriver set', 'price': 24.0, 'stock': 0}
{'id': 4, 'category': 'garden', 'name': 'Watering can', 'price': 9.99, 'stock': 48}

Processing data as it streams

Building a list of all records gives up the main advantage of SAX. When we need only a summary, the handler can compute it while parsing and keep no records at all.

streaming.py
import xml.sax


class StockValue(xml.sax.ContentHandler):

    def __init__(self):
        super().__init__()
        self.text = []
        self.price = 0.0
        self.total = 0.0
        self.out_of_stock = []
        self.name = ""

    def startElement(self, name, attrs):
        self.text = []

    def characters(self, content):
        self.text.append(content)

    def endElement(self, name):
        value = "".join(self.text).strip()
        if name == "name":
            self.name = value
        elif name == "price":
            self.price = float(value)
        elif name == "stock":
            stock = int(value)
            self.total += self.price * stock
            if stock == 0:
                self.out_of_stock.append(self.name)


handler = StockValue()
xml.sax.parse("products.xml", handler)
print(f"stock value: {handler.total:.2f}")
print("out of stock:", handler.out_of_stock)

The handler remembers only the name and price of the current product. When the stock element ends, it adds the value of the product to the total and notes the products that are sold out. The memory use does not depend on the size of the file.

$ python streaming.py
stock value: 1153.02
out of stock: ['Screwdriver set']

Tracking the element path

An element name alone may be ambiguous. In the next file, both customers and items have a name element.

orders.xml
<?xml version="1.0" encoding="UTF-8"?>
<orders>
    <order id="501">
        <customer>
            <name>Anna Kovacova</name>
            <city>Brno</city>
        </customer>
        <item>
            <name>Hammer</name>
            <quantity>2</quantity>
        </item>
        <item>
            <name>Rake</name>
            <quantity>1</quantity>
        </item>
    </order>
    <order id="502">
        <customer>
            <name>Peter Novak</name>
            <city>Zilina</city>
        </customer>
        <item>
            <name>Watering can</name>
            <quantity>3</quantity>
        </item>
    </order>
</orders>

A handler can keep a stack of open elements to know where it is in the document.

path_stack.py
import xml.sax


class OrderHandler(xml.sax.ContentHandler):

    def __init__(self):
        super().__init__()
        self.path = []
        self.text = []

    def startElement(self, name, attrs):
        self.path.append(name)
        self.text = []
        if name == "order":
            print("order", attrs["id"])

    def characters(self, content):
        self.text.append(content)

    def endElement(self, name):
        value = "".join(self.text).strip()
        where = "/".join(self.path[-2:])
        if where == "customer/name":
            print("  customer:", value)
        elif where == "item/name":
            print("  item:", value, end="")
        elif where == "item/quantity":
            print(" x", value)
        self.path.pop()


xml.sax.parse("orders.xml", OrderHandler())

The startElement method pushes each name on the path list and endElement pops it. The last two names on the stack, such as customer/name or item/name, tell the two kinds of names apart.

$ python path_stack.py
order 501
  customer: Anna Kovacova
  item: Hammer x 2
  item: Rake x 1
order 502
  customer: Peter Novak
  item: Watering can x 3

Namespaces

By default, the parser reports qualified names such as geo:lat and ignores namespaces. With the feature_namespaces feature turned on, it resolves the prefixes and calls the startElementNS and endElementNS methods instead.

feed.xml
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
      xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
    <title>Weather stations</title>
    <entry>
        <title>Lomnicky stit</title>
        <geo:lat>49.195</geo:lat>
        <geo:long>20.213</geo:long>
    </entry>
    <entry>
        <title>Chopok</title>
        <geo:lat>48.944</geo:lat>
        <geo:long>19.592</geo:long>
    </entry>
</feed>

The Atom feed uses a default namespace and a second namespace with the geo prefix.

namespaces.py
import xml.sax
from xml.sax.handler import feature_namespaces

ATOM = "http://www.w3.org/2005/Atom"
GEO = "http://www.w3.org/2003/01/geo/wgs84_pos#"


class GeoHandler(xml.sax.ContentHandler):

    def __init__(self):
        super().__init__()
        self.text = []

    def startElementNS(self, name, qname, attrs):
        self.text = []

    def characters(self, content):
        self.text.append(content)

    def endElementNS(self, name, qname):
        uri, local = name
        value = "".join(self.text).strip()
        if uri == ATOM and local == "title":
            print(value)
        elif uri == GEO:
            print(f"  {local}: {value}")


parser = xml.sax.make_parser()
parser.setFeature(feature_namespaces, True)
parser.setContentHandler(GeoHandler())
parser.parse("feed.xml")

Features are set on a parser created with make_parser. The namespace-aware methods receive the name as a pair of namespace URI and local name. The handler matches on the URI, not on the prefix, which the author of a document may choose freely.

$ python namespaces.py
Weather stations
Lomnicky stit
  lat: 49.195
  long: 20.213
Chopok
  lat: 48.944
  long: 19.592

Errors

When a document is not well-formed, the parser raises SAXParseException. The exception knows the position of the error.

errors.py
import xml.sax

documents = [
    "<shelf><book>Dune</book></shelf>",
    "<shelf><book>Dune</shelf>",
    "<shelf>\n  <book>Emma & Co</book>\n</shelf>",
]

for doc in documents:
    try:
        xml.sax.parseString(doc, xml.sax.ContentHandler())
        print("well-formed")
    except xml.sax.SAXParseException as e:
        print(f"line {e.getLineNumber()}, column {e.getColumnNumber()}: "
              f"{e.getMessage()}")

The second document closes shelf while book is still open; the third contains a bare ampersand, which must be written as &amp;. The line and column numbers point to the place where the parser detected the problem; columns are counted from zero. Note that the handler receives all events up to the error, so a SAX program may have processed part of a broken document before it fails.

$ python errors.py
well-formed
line 1, column 19: mismatched tag
line 2, column 14: not well-formed (invalid token)

Stopping early

SAX has no method to stop the parser. A handler that has found what it needs can raise its own exception, which ends the parsing and carries the result out.

stop_early.py
import xml.sax


class Found(Exception):
    pass


class FindProduct(xml.sax.ContentHandler):

    def __init__(self, wanted):
        super().__init__()
        self.wanted = wanted
        self.events = 0

    def startElement(self, name, attrs):
        self.events += 1
        if name == "product" and attrs["id"] == self.wanted:
            raise Found(dict(attrs))


handler = FindProduct("2")
try:
    xml.sax.parse("products.xml", handler)
    print("not found")
except Found as e:
    print("found:", e.args[0], "after", handler.events, "start events")

The handler raises Found at the start of the wanted product. The parser stops immediately, so the rest of the file is never read. This saves time when the item is near the beginning of a large file.

$ python stop_early.py
found: {'id': '2', 'category': 'garden'} after 6 start events

Incremental parsing

The parser returned by make_parser also accepts data piece by piece. The feed method passes a chunk, and close signals the end of the document. This suits data arriving from a network connection.

incremental.py
import xml.sax

chunks = [
    "<readings><t unit='C'>2",
    "1.5</t><t unit='C'>",
    "19.0</t><t un",
    "it='C'>23.25</t></readings>",
]


class Temperatures(xml.sax.ContentHandler):

    def __init__(self):
        super().__init__()
        self.text = []

    def startElement(self, name, attrs):
        self.text = []

    def characters(self, content):
        self.text.append(content)

    def endElement(self, name):
        if name == "t":
            print("temperature:", float("".join(self.text)))


parser = xml.sax.make_parser()
parser.setContentHandler(Temperatures())

for chunk in chunks:
    print("feeding", repr(chunk))
    parser.feed(chunk)
parser.close()

The chunks split the document at arbitrary places, even inside a number and an attribute name. The parser buffers incomplete input and reports each reading as soon as its element is complete. The handler joins the text pieces, so 21.5 is read correctly although it arrived in two chunks.

$ python incremental.py
feeding "<readings><t unit='C'>2"
feeding "1.5</t><t unit='C'>"
temperature: 21.5
feeding '19.0</t><t un'
temperature: 19.0
feeding "it='C'>23.25</t></readings>"
temperature: 23.25

Writing XML

The xml.sax.saxutils module contains XMLGenerator, a handler that writes the events it receives as XML. Calling its methods directly produces a document with correctly escaped text and attributes.

writer.py
import sys
from xml.sax.saxutils import XMLGenerator

products = [
    ("1", "Hammer", "12.90"),
    ("2", "Nuts & bolts", "4.50"),
]

out = XMLGenerator(sys.stdout, encoding="utf-8", short_empty_elements=True)
out.startDocument()
out.startElement("products", {})
for pid, name, price in products:
    out.characters("\n  ")
    out.startElement("product", {"id": pid, "price": price})
    out.characters(name)
    out.endElement("product")
out.characters("\n  ")
out.startElement("discontinued", {})
out.endElement("discontinued")
out.characters("\n")
out.endElement("products")
out.endDocument()
print()

The generator writes to standard output. The ampersand in the product name is escaped automatically, and with short_empty_elements the empty element is written as <discontinued/>. Whitespace for indentation must be added as character data.

$ python writer.py
<?xml version="1.0" encoding="utf-8"?>
<products>
  <product id="1" price="12.90">Hammer</product>
  <product id="2" price="4.50">Nuts &amp; bolts</product>
  <discontinued/>
</products>

Security

XML parsers can be attacked with crafted documents. The SAX parser does not resolve external entities by default, which blocks attacks that read local files, and the bundled Expat library limits the expansion of nested entities. For untrusted input, see the XML security section of the documentation.

Source

xml.sax documentation, xml.sax.handler, xml.sax.saxutils

In this article we have parsed XML with SAX. We have written handlers for element and text events, collected text that arrives in chunks, read attributes, turned elements into records, aggregated data while streaming, tracked the element path, handled namespaces and errors, stopped the parser early, fed it data incrementally, and written XML with XMLGenerator. See also Python XML ElementTree, Python XML minidom, and Python lxml.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.