IC Improve Code Recipes

Recipe 12.4 · Python

LINQ to XML for Documents Without Classes

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

Not every XML document deserves a class. You need three values from a configuration file, a quick transformation of a partner feed, or a small document built from a query. The old way meant XmlDocument, XPath strings and InnerText, or worse, building XML with string concatenation.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

The first block produces invalid XML the day a product called Nuts & Bolts arrives, and its price depends on the server's culture: a German server writes 9,99. The second block throws on the first file that omits an element.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python XML built by string concatenation and read with unchecked XPath lookups (p266_r12_4_string_built_xml_xpath_before.py)
"""XML built by string concatenation and read with unchecked XPath lookups

Source: ImproveCode, Chapter 12, Recipe 12.4 "LINQ to XML for Documents Without Classes"
Section: The way it's often written
Book page: 266  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
XmlDocument/SelectSingleNode -> xml.etree.ElementTree find(); a missing node
gives AttributeError on None (the NullReferenceException analogue).
"""

import xml.etree.ElementTree as ET
from decimal import Decimal
from typing import Any


def build(product: Any) -> str:
    # Not to copy: string-built XML breaks on "&" and "<" in data
    xml = ("<Product><Name>" + product.name + "</Name>" +
           "<Price>" + str(product.price) + "</Price></Product>")
    return xml


def read(path: str) -> tuple[str, Decimal]:
    # Not to copy: NullReferenceException when a node is missing
    doc = ET.parse(path)
    name = doc.find(".//Product/Name").text  # type: ignore[union-attr]
    price = Decimal(doc.find(".//Product/Price").text)  # type: ignore[union-attr, arg-type]
    return name, price  # type: ignore[return-value]

The improved recipe

XDocument builds documents by construction, escapes every value, and reads with explicit casts that return null when something is missing.

Requirements: Python 3.12+. Install: pip install defusedxml

Python Build, parse, safely load and edit a namespaced product catalog XML (p266_r12_4_namespaced_catalog_xml.py)
"""Build, parse, safely load and edit a namespaced product catalog XML

Source: ImproveCode, Chapter 12, Recipe 12.4 "LINQ to XML for Documents Without Classes"
Section: The improved recipe
Book page: 266-267  -- original C# listing
Converted from C# to Python.
LINQ to XML (XDocument/XElement/XNamespace) -> xml.etree.ElementTree with
"{ns}name" tags; safe loading (no DTD/resolver) -> defusedxml; explicit casts
with defaults -> small helper functions; XmlConvert.ToString -> str(Decimal).
"""

from __future__ import annotations

import datetime as dt
import xml.etree.ElementTree as ET
from collections.abc import Iterable
from dataclasses import dataclass
from decimal import ROUND_HALF_EVEN, Decimal

import defusedxml.ElementTree as SafeET

NS = "urn:example:catalog:v1"
ET.register_namespace("", NS)


def _q(name: str) -> str:
    return f"{{{NS}}}{name}"


@dataclass(frozen=True)
class Product:
    sku: str
    name: str
    price: Decimal
    discontinued: dt.datetime | None


def build(products: Iterable[Product]) -> ET.ElementTree:
    catalog = ET.Element(_q("Catalog"), {
        "generated": dt.datetime.now(dt.timezone.utc).isoformat()})
    for p in products:
        product = ET.SubElement(catalog, _q("Product"), {"sku": p.sku})
        ET.SubElement(product, _q("Name")).text = p.name
        ET.SubElement(product, _q("Price")).text = str(p.price)
        if p.discontinued is not None:
            ET.SubElement(product, _q("Discontinued")).text = \
                p.discontinued.isoformat()
    # Write with: tree.write(f, encoding="utf-8", xml_declaration=True)
    return ET.ElementTree(catalog)


def _text(e: ET.Element, name: str) -> str | None:
    child = e.find(_q(name))
    return None if child is None else (child.text or "")


def parse(doc: ET.ElementTree) -> list[Product]:
    root = doc.getroot()
    if root is None:
        return []
    result: list[Product] = []
    for e in root.findall(_q("Product")):
        price = _text(e, "Price")
        discontinued = _text(e, "Discontinued")
        result.append(Product(
            sku=e.get("sku") or "",
            name=_text(e, "Name") or "",
            price=Decimal(price) if price is not None else Decimal(0),
            discontinued=(dt.datetime.fromisoformat(discontinued)
                          if discontinued is not None else None),
        ))
    return result


def load_safely(path: str) -> ET.ElementTree:
    return SafeET.parse(path, forbid_dtd=True)


def raise_prices(doc: ET.ElementTree, factor: Decimal) -> None:
    for price in doc.iter(_q("Price")):
        current = Decimal(price.text or "")
        price.text = str((current * factor).quantize(
            Decimal("0.01"), rounding=ROUND_HALF_EVEN))

How it works

Functional construction mirrors the shape of the document. Each XElement constructor takes a name and any number of children: attributes, elements, sequences of elements, or null, which is skipped. That is why the conditional Discontinued element can return null inline.

Values are converted with XmlConvert, not with the current culture. A decimal becomes 9.99 everywhere, and a DateTime becomes an ISO 8601 string. Text is escaped automatically, so Nuts & Bolts becomes Nuts &amp; Bolts.

On the way back, the explicit conversion operators do the work. (string?)element returns null when the element is missing, and (decimal?)element and (DateTime?)element parse with XmlConvert rules. Combined with ?? you get a default instead of an exception, and the intent is visible on one line.

Namespaces are the part that trips people up. An element written as <Product xmlns="urn:example:catalog:v1"> is not found by Elements("Product"). You must ask for Ns + "Product". Attributes without a prefix are in no namespace, which is why sku is looked up without Ns.

Variations and pitfalls

  • Missing values versus bad values. (decimal?) returns null for a missing element but throws FormatException for <Price>abc</Price>. If partner data is dirty, use decimal.TryParse(e.Element(Ns + "Price")?.Value, NumberStyles.Number, CultureInfo.InvariantCulture, out var price).
  • XPath still works. using System.Xml.XPath; adds XPathSelectElements to XDocument. It is handy for paths copied from a partner's documentation. For anything you write yourself, LINQ queries are easier to read and refactor.
  • Saving. doc.Save(path) writes UTF-8 with a byte-order mark. For BOM-free output, save through an XmlWriter created with new UTF8Encoding(false), as in Recipe 12.3.
  • Large documents. XDocument holds the whole tree in memory, typically several times the file size. Past a few hundred megabytes, switch to the streaming approach in Recipe 12.6.