XML
Beginner
1 min read
DOM Parsing with Python xml.etree.ElementTree
Example
# Python: DOM parsing with xml.etree.ElementTree
import xml.etree.ElementTree as ET
# Parse from a string
xml_string = """<?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>"""
root = ET.fromstring(xml_string)
# Iterate over all book elements
for book in root.findall('book'):
book_id = book.get('id')
category = book.get('category')
title = book.findtext('title')
author = book.findtext('author')
year = book.findtext('year')
price = book.findtext('price')
print(f'[{book_id}] {title} by {author} ({year}) — ${price} [{category}]')
# Modify: add a new book and serialize back to XML
new_book = ET.SubElement(root, 'book')
new_book.set('id', 'b003')
new_book.set('category', 'reference')
ET.SubElement(new_book, 'title').text = 'XML in a Nutshell'
ET.SubElement(new_book, 'author').text = 'Elliotte Rusty Harold'
ET.SubElement(new_book, 'year').text = '2004'
# Serialize (ET.indent available in Python 3.9+)
ET.indent(root, space=' ')
output = ET.tostring(root, encoding='unicode', xml_declaration=False)
print(output[:200])