XML Parsing in Python
Estimated study time: 12 minutes.
Python includes XML parsing support out of the box through the xml.etree.ElementTree module, which offers a simple, tree-based (DOM-like) way to read and search XML documents.
Reading a File
import xml.etree.ElementTree as ET
tree = ET.parse('course.xml')
root = tree.getroot()
print(root.tag) # 'course'
print(root.find('title').text) # 'Data Analytics'
Looping Through Elements
<!-- course.xml -->
<course>
<modules>
<module>Excel Basics</module>
<module>SQL for Analysis</module>
</modules>
</course>
for module in root.find('modules'):
print(module.text)
Reading Attributes
<course id="DA-101" level="beginner">...</course>
print(root.get('id')) # 'DA-101'
print(root.get('level')) # 'beginner'
Parsing from a String
xml_data = "<course><title>Data Analytics</title></course>"
root = ET.fromstring(xml_data)
print(root.find('title').text)
For Very Large Files
For files too large to comfortably load into memory, Python's iterparse() function offers a SAX-like streaming approach, processing elements as they're read rather than loading the whole tree at once.
💡 Tip:
ElementTree handles the vast majority of everyday XML parsing needs in Python — reach for lxml only if you specifically need XPath, XSD validation, or faster performance on very large files.