Use Python’s built-in xml.etree.ElementTree module (ET.parse("file.xml") or ET.fromstring(xml_text)), locate target elements via .find(), .findall(), or .iter(), and read attributes using elem.get("attr_name") (which returns None safely if missing) or elem.attrib["attr_name"]—switching to defusedxml.ElementTree whenever parsing untrusted external XML.
Basic Example
import xml.etree.ElementTree as ET
xml_data = """
<catalog>
<book id="bk101" category="programming" available="true">
<title>Fluent Python</title>
<price currency="USD">59.99</price>
</book>
<book id="bk102" category="data-science">
<title>Python for Data Analysis</title>
<price currency="EUR">49.50</price>
</book>
</catalog>
"""
# 1. Parse from string (or use `tree = ET.parse("catalog.xml")` for files)
root = ET.fromstring(xml_data)
# 2. Iterate matching elements and extract attributes safely with .get()
for book in root.findall("book"):
book_id = book.get("id") # Output: "bk101", "bk102"
status = book.get("available", default="false") # Safe fallback if attribute is absent
price_node = book.find("price")
currency = price_node.get("currency") if price_node is not None else None
print(f"ID={book_id} | available={status} | currency={currency}")
# 3. Filter elements directly by attribute value using XPath predicate
prog_book = root.find(".//book[@id='bk101']")
print(prog_book.attrib)
# Output: {'id': 'bk101', 'category': 'programming', 'available': 'true'}
Key Details & Edge Cases
elem.get("attr")vs.elem.attrib["attr"]:elem.attribis a standard Pythondictmapping attribute names to strings ({'id': 'bk101', ...}).- Accessing
elem.attrib["available"]raises aKeyErrorif that optional attribute is omitted on a node (likebk102above). Always preferelem.get("available")(orelem.get("available", "default")) for optional attributes.
- Handling XML namespaces (
xmlns="http://...")—the #1 cause of empty.findall()results:- If your XML declares a default namespace (
<feed xmlns="http://www.w3.org/2005/Atom">),root.findall("entry")silently returns[]because ElementTree expands every tag internally to"{http://www.w3.org/2005/Atom}entry". - Pass an explicit namespace mapping dictionary as the second argument:
ns = {"atom": "[http://www.w3.org/2005/Atom](http://www.w3.org/2005/Atom)"} entries = root.findall("atom:entry", namespaces=ns)
- If your XML declares a default namespace (
- Supported XPath subset in
ElementTreevs. full XPath inlxml:- Built-in
xml.etree.ElementTreesupports a useful XPath subset (.//tag,tag[],tag[='val'],tag[child='text'],*,..), not full XPath 1.0 (such asstandalone attribute selection,contains(), orstarts-with()). Installlxml(from lxml import etree) when you need full XPath 1.0 queries or HTML/malformed XML recovery.
- Built-in
- Security warning for untrusted XML (
defusedxml):- Python’s standard
xml.etree.ElementTreeis vulnerable to XML entity expansion attacks (such as the “Billion Laughs” DoS attack). When parsing XML uploaded by external users or third-party webhooks, drop inimport defusedxml.ElementTree as ET(pip install defusedxml)—it shares the exact same API while blocking malicious entity payloads.
- Python’s standard
- Large multi-gigabyte XML files (
ET.iterparse()):ET.parse()loads the entire XML DOM tree into RAM. For huge XML dumps, stream elements incrementally withfor event, elem in ET.iterparse("huge.xml", events=("end",)):and callelem.clear()after extracting attributes to keep memory usage constant.
Comparison of XML Parsing & Attribute Extraction Options in Python
| Library / Method | Built-In? | XPath Support | Safe Against Untrusted XML DoS? | Best Used When |
|---|---|---|---|---|
xml.etree.ElementTree (ET.parse / ET.fromstring) |
Yes (stdlib) | Basic subset ([@attr='val'], .//tag) |
No (vulnerable to entity bombs) | Trusted internal XML config files, feeds, and moderate-sized documents. |
defusedxml.ElementTree |
No (pip install defusedxml) |
Same subset as stdlib ET |
Yes | Parsing untrusted user-uploaded XML, SOAP payloads, or external webhooks. |
ET.iterparse() |
Yes (stdlib) | Event-driven streaming | No | Processing multi-gigabyte XML files without loading the whole tree into RAM. |
lxml.etree |
No (pip install lxml) |
Full XPath 1.0 + XSLT + XSD | Configurable (XMLParser(resolve_entities=False)) |
Complex XPath queries, schema validation, or high-speed C-level XML processing. |
You must log in or register to comment.
