Skip to main content
Albero Academy

XML

Parse XML documents with ElementTree.

File Handling8 min

XML is a verbose but still-common format — you'll meet it in configuration files, RSS/Atom feeds, office documents, and enterprise/legacy systems. Python's built-in xml.etree.ElementTree parses it into a navigable tree of elements.

Parsing & navigating

An XML document is a tree: a root element with nested children, each with tags, text, and attributes:

ElementTree
import xml.etree.ElementTree as ET
tree = ET.parse("students.xml")
root = tree.getroot()
for student in root.findall("student"): # all <student> children
name = student.find("name").text # nested <name> text
track = student.get("track") # an attribute
print(name, track)

find returns the first matching child, findall returns all of them, .text reads element content, and .get("attr") reads an attribute.

Parse untrusted XML safely

Key takeaways

  1. 01ElementTree parses XML into a tree of elements.
  2. 02find (first) / findall (all) navigate; .text reads content, .get() reads attributes.
  3. 03XML is common in config, feeds and legacy/enterprise systems.
  4. 04For untrusted XML, use defusedxml to avoid entity-expansion attacks.
  5. 05Prefer JSON when you have the choice.

Finished this chapter?

Mark it complete to track your progress through Python.