Parse an XML file in Python with the standard library: tree = ET.parse("file.xml"), then root = tree.getroot() and loop over root.findall("book") to read tags, attributes and text. xml.etree.ElementTree handles small and medium files well and needs no installation.
This guide covers loading, navigating with find and XPath-style paths, attributes, namespaces, modifying and writing XML, streaming large files with iterparse, and the security caveats for untrusted input.
Save this as library.xml:
Parse it and print each book:
ET.parse() accepts a filename or file object and returns an ElementTree. To parse a string instead, use ET.fromstring(xml_text), which returns the root element directly. All text values are strings, so convert numbers yourself.
Each element has .tag, .attrib (a dictionary), .text and child elements. Useful lookups:
| Call | Returns |
|---|---|
root.find("book") | First matching direct child, or None |
root.findall("book") | List of matching direct children |
root.iter("title") | Every title anywhere below, lazily |
root.findall(".//book[@id='2']") | Descendants matching a limited XPath |
elem.get("id", "default") | Attribute value or default |
elem.findtext("year", default="") | Text of a child, safe if missing |
find() returns None when nothing matches, so book.find("title").text raises an AttributeError on a missing tag. Prefer findtext() or check for None first. ElementTree supports only a subset of XPath. For full XPath 1.0, XSLT or schema validation, use the third-party lxml package.
If the document declares a namespace, tags include the URI and plain names no longer match.
The prefix in your mapping is local to your code; only the URI has to match the document.
Elements are mutable, so you can add, change and remove them, then save the tree.
ET.indent() pretty-prints the tree and was added in Python 3.9. Without the xml_declaration=True argument, no <?xml ...?> line is written. Removing items while looping over the same list can skip elements, so loop over a copy such as list(root) when you remove several.
parse() loads the whole document into memory. For files of hundreds of megabytes, stream the events and free memory as you go.
Clearing each finished element keeps memory use roughly flat. Only act on an element at its end event, because its children are not yet complete at start.
ElementTree is not designed to defend against malicious input. The Python documentation warns that it is vulnerable to attacks such as exponential entity expansion (the "billion laughs" attack). For XML from users or the network, use the defusedxml package, which provides drop-in replacements:
Install it with pip install defusedxml. Never build XML by concatenating strings from user input; create elements with the API so special characters are escaped.
| Library | Use it when |
|---|---|
xml.etree.ElementTree | Everyday parsing and generation, no dependencies |
lxml | Full XPath, XSLT, schema validation, speed |
xml.dom.minidom | You specifically need the DOM API |
xml.sax | Event-based parsing, old style |
xmltodict | You want XML as nested dictionaries |
Use element.get("name") or element.attrib["name"]. get() returns None, or a default you pass, when the attribute is missing.
find() return None?The path did not match. Check spelling and case, remember that find() only searches direct children, use .// for deeper levels, and account for namespaces.
Call ET.indent(tree) (Python 3.9+) before writing or converting to a string with ET.tostring(root, encoding="unicode").
No. Use lxml or another validator for schema validation.
Use ET.parse() and getroot() to load a file, find, findall and findtext to navigate, and tree.write() to save changes. Handle namespaces with a prefix mapping, stream large documents with iterparse, and use defusedxml or lxml when the input is untrusted or you need advanced features.