XML
Beginner
2 min read
SAX Parsing with Python xml.sax
Example
# Python: SAX parsing with xml.sax
import xml.sax
import xml.sax.handler
class BookHandler(xml.sax.ContentHandler):
"""Extract book records from the library XML."""
def __init__(self):
super().__init__()
self.books = []
self._current = {}
self._current_tag = None
self._buffer = []
def startElement(self, name, attrs):
self._current_tag = name
self._buffer = []
if name == 'book':
# attrs is an AttributesImpl object
self._current = {
'id': attrs.get('id', ''),
'category': attrs.get('category', ''),
}
def characters(self, content):
# May be called multiple times for one text node
self._buffer.append(content)
def endElement(self, name):
text = ''.join(self._buffer).strip()
if name in ('title', 'author', 'year', 'price'):
self._current[name] = text
elif name == 'book':
self.books.append(dict(self._current))
self._current = {}
self._current_tag = None
self._buffer = []
def endDocument(self):
print(f'Parsing complete. {len(self.books)} books found.')
import io
xml_bytes = b"""<?xml version="1.0" encoding="UTF-8"?>
<library>
<book id="b001" category="fiction">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<year>1925</year><price>12.99</price>
</book>
<book id="b002" category="non-fiction">
<title>Clean Code</title>
<author>Robert C. Martin</author>
<year>2008</year><price>35.00</price>
</book>
</library>"""
handler = BookHandler()
xml.sax.parseString(xml_bytes, handler)
for b in handler.books:
print(b)