Claude Code for xml.dom.pulldom: Python Pull-Mode XML Parser — Claude Skills 360 Blog
Blog / AI / Claude Code for xml.dom.pulldom: Python Pull-Mode XML Parser
AI

Claude Code for xml.dom.pulldom: Python Pull-Mode XML Parser

Published: January 27, 2029
Read time: 5 min read
By: Claude Skills 360

Python’s xml.dom.pulldom module provides a hybrid SAX/DOM parser: it produces a lazy event stream like SAX but lets you optionally expand any element into a full DOM subtree (like minidom) on demand. from xml.dom import pulldom. Parse file: events = pulldom.parse("data.xml"). Parse string: events = pulldom.parseString(b"<root/>"). Iterate: for event, node in events: — event is one of the constants pulldom.START_ELEMENT, END_ELEMENT, CHARACTERS, PROCESSING_INSTRUCTION, COMMENT, IGNORABLE_WHITESPACE, START_DOCUMENT, END_DOCUMENT. Expand: events.expandNode(node) — reads ahead in the stream to build the node’s full DOM subtree in memory; call only on START_ELEMENT nodes you want to process deeply, skip the rest. The key advantage over SAX: you can ignore most of the document at SAX speed and call expandNode() only on the elements you care about, avoiding loading the full document into memory like minidom would. Claude Code generates memory-efficient XML stream processors, selective element extractors, large-file RSS readers, XML-to-JSON converters, and document-structure validators.

CLAUDE.md for xml.dom.pulldom

## xml.dom.pulldom Stack
- Stdlib: from xml.dom import pulldom
- Parse file:   events = pulldom.parse("data.xml")
- Parse bytes:  events = pulldom.parseString(xml_bytes)
- Iterate:  for event, node in events: ...
- Events:   pulldom.START_ELEMENT / END_ELEMENT / CHARACTERS
-           PROCESSING_INSTRUCTION / COMMENT / START_DOCUMENT
- Expand:   events.expandNode(node)   # build full DOM subtree
-           # then use node as minidom Node: node.toxml()
- Pattern:  check START_ELEMENT + node.tagName → expandNode() → process

xml.dom.pulldom Streaming Parser Pipeline

# app/pulldomutil.py — iterate, extract, count, convert, validate, stream-large
from __future__ import annotations

from xml.dom import pulldom, minidom
from typing import Any, Iterator
from dataclasses import dataclass, field
import io


# ─────────────────────────────────────────────────────────────────────────────
# 1. Event stream introspection helpers
# ─────────────────────────────────────────────────────────────────────────────

EVENT_NAMES = {
    pulldom.START_ELEMENT:          "START_ELEMENT",
    pulldom.END_ELEMENT:            "END_ELEMENT",
    pulldom.CHARACTERS:             "CHARACTERS",
    pulldom.PROCESSING_INSTRUCTION: "PROCESSING_INSTRUCTION",
    pulldom.COMMENT:                "COMMENT",
    pulldom.IGNORABLE_WHITESPACE:   "IGNORABLE_WHITESPACE",
    pulldom.START_DOCUMENT:         "START_DOCUMENT",
    pulldom.END_DOCUMENT:           "END_DOCUMENT",
}


def event_name(evt: int) -> str:
    """
    Return the human-readable name of a pulldom event constant.

    Example:
        event_name(pulldom.START_ELEMENT)   # "START_ELEMENT"
    """
    return EVENT_NAMES.get(evt, f"UNKNOWN({evt})")


def iter_start_elements(xml_source: "str | bytes | io.IOBase",
                         tag: str | None = None) -> Iterator[minidom.Element]:
    """
    Yield fully-expanded DOM elements from an XML source.
    If tag is given, only elements with that tag name are yielded.
    Skips all other events without building DOM nodes.

    Example:
        for el in iter_start_elements(xml_bytes, "item"):
            print(el.getAttribute("id"))
    """
    if isinstance(xml_source, (str, bytes)):
        events = pulldom.parseString(
            xml_source if isinstance(xml_source, bytes)
            else xml_source.encode("utf-8"))
    else:
        events = pulldom.parse(xml_source)

    for event, node in events:
        if event == pulldom.START_ELEMENT:
            if tag is None or node.tagName == tag:
                events.expandNode(node)
                yield node


# ─────────────────────────────────────────────────────────────────────────────
# 2. Element counter (SAX-speed, no DOM expansion)
# ─────────────────────────────────────────────────────────────────────────────

def count_elements(xml_source: "str | bytes",
                   tag: str | None = None) -> dict[str, int]:
    """
    Count element occurrences without expanding any nodes.
    If tag is given, count only that tag; otherwise count all.
    Returns {tag: count}.

    Example:
        counts = count_elements(xml_bytes)
        counts = count_elements(xml_bytes, "item")
    """
    if isinstance(xml_source, str):
        xml_source = xml_source.encode("utf-8")
    events = pulldom.parseString(xml_source)
    counts: dict[str, int] = {}
    for event, node in events:
        if event == pulldom.START_ELEMENT:
            name = node.tagName
            if tag is None or name == tag:
                counts[name] = counts.get(name, 0) + 1
    return counts


# ─────────────────────────────────────────────────────────────────────────────
# 3. Selective element extractor
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class ExtractedElement:
    tag:        str
    attributes: dict[str, str]
    text:       str
    xml:        str   # serialised to XML string


def extract_elements(xml_source: "str | bytes",
                     tag: str,
                     max_items: int = 1000) -> list[ExtractedElement]:
    """
    Extract all elements with the given tag name into ExtractedElement records.
    expandNode() is called only for matching elements.

    Example:
        items = extract_elements(rss_bytes, "item", max_items=50)
        for item in items:
            print(item.attributes, item.text[:80])
    """
    if isinstance(xml_source, str):
        xml_source = xml_source.encode("utf-8")
    results: list[ExtractedElement] = []
    events = pulldom.parseString(xml_source)
    for event, node in events:
        if len(results) >= max_items:
            break
        if event == pulldom.START_ELEMENT and node.tagName == tag:
            events.expandNode(node)
            attrs = {}
            for i in range(node.attributes.length):
                a = node.attributes.item(i)
                attrs[a.name] = a.value
            texts: list[str] = []
            for child in node.childNodes:
                if child.nodeType == child.TEXT_NODE:
                    texts.append(child.data)
                elif child.nodeType == child.ELEMENT_NODE:
                    for sub in child.childNodes:
                        if sub.nodeType == sub.TEXT_NODE:
                            texts.append(sub.data)
            results.append(ExtractedElement(
                tag=node.tagName,
                attributes=attrs,
                text="".join(texts).strip(),
                xml=node.toxml(),
            ))
    return results


# ─────────────────────────────────────────────────────────────────────────────
# 4. XML-to-dict with selective expand
# ─────────────────────────────────────────────────────────────────────────────

def node_to_dict(node: Any) -> Any:
    """
    Recursively convert a minidom Node subtree to a Python dict/list/str.

    Example:
        for el in iter_start_elements(xml, "record"):
            d = node_to_dict(el)
            print(d)
    """
    if node.nodeType == node.TEXT_NODE:
        return node.data.strip()
    if node.nodeType == node.ELEMENT_NODE:
        result: dict[str, Any] = {}
        # attributes
        for i in range(node.attributes.length):
            a = node.attributes.item(i)
            result[f"@{a.name}"] = a.value
        # children
        children = [c for c in node.childNodes
                    if c.nodeType in (c.ELEMENT_NODE, c.TEXT_NODE)]
        for child in children:
            key = child.nodeName if child.nodeType == child.ELEMENT_NODE else "#text"
            val = node_to_dict(child)
            if not val:
                continue
            if key in result:
                existing = result[key]
                if not isinstance(existing, list):
                    result[key] = [existing]
                result[key].append(val)
            else:
                result[key] = val
        if not result:
            return ""
        if list(result.keys()) == ["#text"]:
            return result["#text"]
        return result
    return ""


def xml_to_dicts(xml_source: "str | bytes",
                  root_tag: str) -> list[dict]:
    """
    Parse XML and return a list of dicts for elements matching root_tag.

    Example:
        records = xml_to_dicts(xml_bytes, "person")
        for r in records:
            print(r.get("name"), r.get("email"))
    """
    return [node_to_dict(el)
            for el in iter_start_elements(xml_source, root_tag)]


# ─────────────────────────────────────────────────────────────────────────────
# 5. Structure validator
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class ValidationReport:
    valid:               bool
    element_count:       int
    depth_max:           int
    required_tags_found: list[str]
    required_tags_missing: list[str]
    errors:              list[str] = field(default_factory=list)


def validate_xml_structure(xml_source: "str | bytes",
                            required_tags: list[str] | None = None) -> ValidationReport:
    """
    Validate that an XML document is well-formed and contains required tags.

    Example:
        report = validate_xml_structure(xml_bytes, required_tags=["title", "item"])
        print(report.valid, report.required_tags_missing)
    """
    if isinstance(xml_source, str):
        xml_source = xml_source.encode("utf-8")
    required_tags = required_tags or []
    found_tags: set[str] = set()
    element_count = 0
    depth = 0
    depth_max = 0
    errors: list[str] = []

    try:
        events = pulldom.parseString(xml_source)
        for event, node in events:
            if event == pulldom.START_ELEMENT:
                element_count += 1
                depth += 1
                depth_max = max(depth_max, depth)
                found_tags.add(node.tagName)
            elif event == pulldom.END_ELEMENT:
                depth -= 1
    except Exception as e:
        errors.append(f"parse error: {e}")

    found = [t for t in required_tags if t in found_tags]
    missing = [t for t in required_tags if t not in found_tags]
    return ValidationReport(
        valid=len(errors) == 0,
        element_count=element_count,
        depth_max=depth_max,
        required_tags_found=found,
        required_tags_missing=missing,
        errors=errors,
    )


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    print("=== xml.dom.pulldom demo ===")

    sample_xml = b"""<?xml version="1.0"?>
<catalog>
  <book id="b1" lang="en">
    <title>Python Cookbook</title>
    <author>David Beazley</author>
    <price>39.99</price>
  </book>
  <book id="b2" lang="fr">
    <title>Apprendre Python</title>
    <author>Mark Lutz</author>
    <price>29.99</price>
  </book>
  <magazine id="m1">
    <title>Python Weekly</title>
  </magazine>
</catalog>"""

    # ── count_elements ────────────────────────────────────────────────────────
    print("\n--- count_elements ---")
    counts = count_elements(sample_xml)
    for name, n in sorted(counts.items()):
        print(f"  {name:15s}: {n}")

    # ── extract_elements ──────────────────────────────────────────────────────
    print("\n--- extract_elements (book) ---")
    books = extract_elements(sample_xml, "book")
    for b in books:
        print(f"  id={b.attributes.get('id')}  "
              f"lang={b.attributes.get('lang')}  "
              f"text={b.text[:30]!r}")

    # ── xml_to_dicts ──────────────────────────────────────────────────────────
    print("\n--- xml_to_dicts (book) ---")
    for d in xml_to_dicts(sample_xml, "book"):
        print(f"  {d}")

    # ── validate_xml_structure ────────────────────────────────────────────────
    print("\n--- validate_xml_structure ---")
    report = validate_xml_structure(
        sample_xml, required_tags=["title", "author", "isbn"])
    print(f"  valid         = {report.valid}")
    print(f"  element_count = {report.element_count}")
    print(f"  depth_max     = {report.depth_max}")
    print(f"  found         = {report.required_tags_found}")
    print(f"  missing       = {report.required_tags_missing}")

    # ── event_name ────────────────────────────────────────────────────────────
    print("\n--- event names ---")
    for k, name in list(EVENT_NAMES.items())[:5]:
        print(f"  {k}: {name}")

    print("\n=== done ===")

For the xml.etree.ElementTree stdlib alternative — ET.iterparse(source, events=("start","end")) provides a similar pull-parsing API with lower overhead per event and a simpler elem.clear() pattern for streaming large files — use iterparse with elem.clear() for most large-XML streaming tasks as it is faster and has a cleaner API; use pulldom when you need selective DOM expansion of matched elements to exploit minidom’s Node.toxml(), XPath-like traversal, or namespace resolution. For the lxml.etree (PyPI) alternative — lxml.etree.iterparse(file, events=("start","end","start-ns")) is 3–10× faster than stdlib XML parsing and adds DTD/schema validation, XPath/XSLT, and better namespace handling — use lxml for production XML processing of large or complex documents. The Claude Skills 360 bundle includes xml.dom.pulldom skill sets covering event_name()/iter_start_elements() event helpers, count_elements() SAX-speed counter, ExtractedElement/extract_elements() selective extractor, node_to_dict()/xml_to_dicts() converter, and ValidationReport/validate_xml_structure() structure validator. Start with the free tier to try pull-mode XML patterns and pulldom pipeline code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free