Recipe 12.3 · Python
XmlSerializer Without the Leaks
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
- The way it's often written
- The improved recipe
- How it works
- Variations and pitfalls
- On .NET Framework
Problem
A trading partner sends invoices as XML, and you would rather work with a class than with nodes.
XmlSerializer does that job well, but it has a few traps: one constructor overload leaks memory,
StringWriter produces a UTF-16 declaration your partner rejects, the output carries namespace
declarations nobody asked for, and default reader settings are more trusting than they should be.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
XmlSerializer generates and loads a dynamic assembly for each type it handles. The
XmlSerializer(Type) and XmlSerializer(Type, string) constructors cache that assembly. Every
other overload, including the one that takes an XmlRootAttribute, generates a fresh assembly on
every call, and assemblies are never unloaded. I once traced an app pool that recycled every few
hours to exactly this line in a helper class.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""XML helpers that build a serializer per call and parse with DTDs enabled
Source: ImproveCode, Chapter 12, Recipe 12.3 "XmlSerializer Without the Leaks"
Section: The way it's often written
Book page: 261-262 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
XmlSerializer -> the dataclass XmlSerializer from p262, constructed on every
call (Python does not leak an assembly, but the per-call build cost remains);
StringWriter's UTF-16 header and xsi/xsd namespaces are reproduced; XmlDocument
-> xml.dom.minidom, which expands internal DTD entities.
"""
# Not to copy: leaks an assembly per call, UTF-16 header, xsi/xsd noise
from typing import Any, TypeVar
from xml.dom import minidom
import xml.etree.ElementTree as ET
from p262_r12_3_cached_safe_xml_helper import XmlSerializer
T = TypeVar("T")
def to_xml(value: Any) -> str:
serializer = XmlSerializer(type(value), root_name="Invoice")
root = serializer.to_element(value)
root.set("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
root.set("xmlns:xsd", "http://www.w3.org/2001/XMLSchema")
return ('<?xml version="1.0" encoding="utf-16"?>'
+ ET.tostring(root, encoding="unicode"))
def from_xml(xml: str, cls: type[T]) -> T:
doc = minidom.parseString(xml) # DTDs on older frameworks
serializer = XmlSerializer(cls)
return serializer.from_element(ET.fromstring(doc.toxml()))
The improved recipe
Cache serializers yourself, keyed by type and root name. Write UTF-8 without a byte-order mark,
suppress the default namespaces, and read through an XmlReader that refuses DTDs.
A class shaped for XmlSerializer looks like this:
Requirements: Python 3.12+. Install: pip install defusedxml
"""Cached XML serializers with safe reader settings and clean UTF-8 output
Source: ImproveCode, Chapter 12, Recipe 12.3 "XmlSerializer Without the Leaks"
Section: The improved recipe
Book page: 262-263 -- original C# listing
Converted from C# to Python.
Python has no XmlSerializer, so a small dataclass-driven XmlSerializer is
included (field metadata mirrors [XmlAttribute]/[XmlElement]/[XmlArray]/[XmlText]).
DtdProcessing.Prohibit -> defusedxml (forbid_dtd=True); ConcurrentDictionary
cache -> dict + lock; XmlWriterSettings(UTF-8 no BOM, indent) -> ET.indent.
"""
from __future__ import annotations
import dataclasses
import datetime as dt
import io
import threading
import typing
import xml.etree.ElementTree as ET
from decimal import Decimal
from typing import Any, BinaryIO, TypeVar
import defusedxml.ElementTree as SafeET
T = TypeVar("T")
class InvalidDataError(ValueError):
"""Equivalent of System.IO.InvalidDataException."""
def xml(kind: str = "element", name: str | None = None,
item: str | None = None, data_type: str | None = None) -> dict[str, Any]:
"""Field metadata: kind is 'element', 'attribute', 'text' or 'array'."""
return {"xml": {"kind": kind, "name": name, "item": item,
"data_type": data_type}}
def _to_text(value: Any, data_type: str | None) -> str:
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, dt.datetime):
return value.date().isoformat() if data_type == "date" else value.isoformat()
if isinstance(value, dt.date):
return value.isoformat()
return str(value)
def _from_text(text: str, tp: Any) -> Any:
if tp is bool:
return text.strip() in ("true", "1")
if tp is int:
return int(text)
if tp is Decimal:
return Decimal(text)
if tp is float:
return float(text)
if tp is dt.datetime:
return dt.datetime.fromisoformat(text)
if tp is dt.date:
return dt.date.fromisoformat(text)
return text
class XmlSerializer:
"""Maps a dataclass to and from an ElementTree element."""
def __init__(self, cls: type, root_name: str | None = None) -> None:
if not dataclasses.is_dataclass(cls):
raise TypeError(f"{cls.__name__} is not a dataclass")
self._cls = cls
self._root = root_name or getattr(cls, "__xml_root__", cls.__name__)
self._hints = typing.get_type_hints(cls)
def to_element(self, value: Any, name: str | None = None) -> ET.Element:
element = ET.Element(name or self._root)
for f in dataclasses.fields(self._cls):
meta = f.metadata.get("xml", {"kind": "element"})
tag = meta.get("name") or f.name
v = getattr(value, f.name)
if v is None:
continue
match meta["kind"]:
case "attribute":
element.set(tag, _to_text(v, meta.get("data_type")))
case "text":
element.text = _to_text(v, meta.get("data_type"))
case "array":
container = ET.SubElement(element, tag)
item_type = typing.get_args(self._hints[f.name])[0]
child = XmlSerializer(item_type)
for item in v:
container.append(child.to_element(
item, meta.get("item") or item_type.__name__))
case _:
if dataclasses.is_dataclass(v):
element.append(XmlSerializer(type(v)).to_element(v, tag))
else:
ET.SubElement(element, tag).text = _to_text(
v, meta.get("data_type"))
return element
def from_element(self, element: ET.Element) -> Any:
if element.tag != self._root:
raise InvalidDataError(
f"Expected <{self._root}> but found <{element.tag}>.")
return self._read(element)
def _read(self, element: ET.Element) -> Any:
kwargs: dict[str, Any] = {}
for f in dataclasses.fields(self._cls):
meta = f.metadata.get("xml", {"kind": "element"})
tag = meta.get("name") or f.name
tp = self._hints[f.name]
match meta["kind"]:
case "attribute":
if (raw := element.get(tag)) is not None:
kwargs[f.name] = _from_text(raw, tp)
case "text":
if element.text is not None:
kwargs[f.name] = _from_text(element.text, tp)
case "array":
item_type = typing.get_args(tp)[0]
child = XmlSerializer(item_type)
container = element.find(tag)
items = [] if container is None else container.findall(
meta.get("item") or item_type.__name__)
kwargs[f.name] = [child._read(e) for e in items]
case _:
node = element.find(tag)
if node is None:
continue
if dataclasses.is_dataclass(tp):
kwargs[f.name] = XmlSerializer(tp)._read(node)
else:
kwargs[f.name] = _from_text(node.text or "", tp)
return self._cls(**kwargs)
class XmlHelper:
_cache: dict[tuple[type, str | None], XmlSerializer] = {}
_lock = threading.Lock()
@staticmethod
def serialize_to_stream(value: Any, stream: BinaryIO,
root_name: str | None = None) -> None:
root = XmlHelper._get_serializer(type(value), root_name).to_element(value)
ET.indent(root)
# UTF-8 without BOM, no xsi/xsd namespace declarations.
ET.ElementTree(root).write(stream, encoding="utf-8", xml_declaration=True)
@staticmethod
def serialize(value: Any, root_name: str | None = None) -> str:
stream = io.BytesIO()
XmlHelper.serialize_to_stream(value, stream, root_name)
return stream.getvalue().decode("utf-8")
@staticmethod
def deserialize_stream(stream: BinaryIO, cls: type[T],
root_name: str | None = None) -> T:
root = SafeET.parse(stream, forbid_dtd=True).getroot()
return XmlHelper._read(root, cls, root_name)
@staticmethod
def deserialize(xml_text: str, cls: type[T],
root_name: str | None = None) -> T:
root = SafeET.fromstring(xml_text, forbid_dtd=True)
return XmlHelper._read(root, cls, root_name)
@staticmethod
def _read(root: ET.Element, cls: type[T], root_name: str | None) -> T:
result = XmlHelper._get_serializer(cls, root_name).from_element(root)
if not isinstance(result, cls):
raise InvalidDataError(f"XML did not contain a {cls.__name__}.")
return result
@staticmethod
def _get_serializer(tp: type, root_name: str | None) -> XmlSerializer:
key = (tp, root_name)
with XmlHelper._lock:
serializer = XmlHelper._cache.get(key)
if serializer is None:
serializer = XmlSerializer(tp, root_name)
XmlHelper._cache[key] = serializer
return serializer
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Invoice XML shape declared with attribute, element, array and text mappings
Source: ImproveCode, Chapter 12, Recipe 12.3 "XmlSerializer Without the Leaks"
Section: The improved recipe
Book page: 264 -- original C# listing
Converted from C# to Python.
[XmlRoot]/[XmlAttribute]/[XmlElement(DataType="date")]/[XmlArray]/[XmlText]
-> dataclass field metadata read by the XmlSerializer in p262.
"""
from __future__ import annotations
import datetime as dt
from dataclasses import dataclass, field
from decimal import Decimal
from typing import ClassVar
from p262_r12_3_cached_safe_xml_helper import xml
@dataclass
class InvoiceLineXml:
sku: str = field(default="", metadata=xml("attribute", "sku"))
quantity: int = field(default=0, metadata=xml("attribute", "qty"))
amount: Decimal = field(default=Decimal(0), metadata=xml("text"))
@dataclass
class InvoiceXml:
__xml_root__: ClassVar[str] = "Invoice"
number: str = field(default="", metadata=xml("attribute", "number"))
issued_on: dt.datetime = field(
default=dt.datetime.min,
metadata=xml("element", "IssuedOn", data_type="date"))
customer: str = field(default="", metadata=xml("element", "Customer"))
lines: list[InvoiceLineXml] = field(
default_factory=list, metadata=xml("array", "Lines", item="Line"))
How it works
The cache key is a tuple of the type and the optional root name, so each combination builds its
serializer exactly once per process. ConcurrentDictionary.GetOrAdd may run the factory twice
under a race, which costs one extra serializer at most, never one per call.
Writing through an XmlWriter over a Stream with new UTF8Encoding(false) gives a declaration
of encoding="utf-8" and no byte-order mark. Writing to a StringWriter would declare UTF-16,
because .NET strings are UTF-16, and partners who validate the header reject it. The empty
XmlSerializerNamespaces removes the xmlns:xsi and xmlns:xsd declarations the serializer adds
by default.
On the reading side, DtdProcessing.Prohibit and a null XmlResolver stop entity-expansion
attacks and external entity references (XXE) from files you did not write. Modern .NET is safe by
default here, but stating the settings documents the intent and keeps the code safe if it is ever
copied back to an older framework.
DataType = "date" writes 2025-03-31 instead of a full timestamp, which is what most invoice
schemas expect. [XmlText] puts the amount in the element body, so a line reads
<Line sku="A-100" qty="2">19.98</Line>.
Variations and pitfalls
- XmlSerializer needs a public parameterless constructor and public settable properties.
Records with positional parameters and
init-only properties don't work. Keep XML-shaped classes separate from your domain types and map between them. DateTimeOffsetis not supported. It serializes as an empty element. UseDateTimewithDataType = "dateTime", or a string property that you parse.- Optional value types. For an element that may be absent, add a
bool QuantitySpecifiedproperty next toQuantity. The serializer reads and writes it by convention. - Interfaces and dictionaries cannot be serialized. Use concrete lists, or a list of key-value classes.
- Validating against a schema. If the partner provides an XSD, add it to
XmlReaderSettings.Schemas, setValidationType = ValidationType.Schema, and handleValidationEventHandler. Reject the file before you deserialize it.
On .NET Framework
The helper works unchanged on .NET Framework 4.7.2 and later once you replace the collection
expressions with new List<...>(). On versions before 4.5.2, XmlDocument and XmlTextReader
resolve external entities by default, so the explicit reader settings are not optional there.