How do you parse XML in Python and extract specific node attributes? | A1Lab@MZeeshanM to PythonEnglish • 4 days ago

How do you parse XML in Python and extract specific node attributes?

message-square
0

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.attrib is a standard Python dict mapping attribute names to strings ({'id': 'bk101', ...}).
    • Accessing elem.attrib["available"] raises a KeyError if that optional attribute is omitted on a node (like bk102 above). Always prefer elem.get("available") (or elem.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)
      
  • Supported XPath subset in ElementTree vs. full XPath in lxml:
    • Built-in xml.etree.ElementTree supports a useful XPath subset (.//tag, tag[@attr], tag[@attr='val'], tag[child='text'], *, ..), not full XPath 1.0 (such as @attr standalone attribute selection, contains(), or starts-with()). Install lxml (from lxml import etree) when you need full XPath 1.0 queries or HTML/malformed XML recovery.
  • Security warning for untrusted XML (defusedxml):
    • Python’s standard xml.etree.ElementTree is 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 in import defusedxml.ElementTree as ET (pip install defusedxml)—it shares the exact same API while blocking malicious entity payloads.
  • Large multi-gigabyte XML files (ET.iterparse()):
    • ET.parse() loads the entire XML DOM tree into RAM. For huge XML dumps, stream elements incrementally with for event, elem in ET.iterparse("huge.xml", events=("end",)): and call elem.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.