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:
import xml.etree.ElementTree as ETtree = ET.parse("students.xml")root = tree.getroot()for student in root.findall("student"): # all <student> childrenname = student.find("name").text # nested <name> texttrack = student.get("track") # an attributeprint(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
- 01ElementTree parses XML into a tree of elements.
- 02find (first) / findall (all) navigate; .text reads content, .get() reads attributes.
- 03XML is common in config, feeds and legacy/enterprise systems.
- 04For untrusted XML, use defusedxml to avoid entity-expansion attacks.
- 05Prefer JSON when you have the choice.
