Python - XML

Overview

Estimated time: 20–30 minutes

Use the standard library’s xml.etree.ElementTree to parse and generate XML. Learn tree navigation, namespaces, and common pitfalls.

Learning Objectives

  • Parse and query XML safely.
  • Build and write XML with proper namespaces.
  • Know when to use lxml for advanced needs.

Examples

import xml.etree.ElementTree as ET

data = """

  Ada

"""
root = ET.fromstring(data)
for p in root.findall("person"):
    print(p.findtext("name"))

Guidance & Patterns

  • Use findall/findtext; handle namespaces with maps.
  • For large files, use iterparse to stream and reduce memory.

Best Practices

  • Be cautious parsing untrusted XML; consider defusedxml.

Exercises

  1. Parse an XML file and convert it to a list of dicts.
  2. Build an XML tree from Python objects and write it to disk.