Claude Code for xml.etree.ElementTree: Python XML Parsing and Generation — Claude Skills 360 Blog
Blog / AI / Claude Code for xml.etree.ElementTree: Python XML Parsing and Generation
AI

Claude Code for xml.etree.ElementTree: Python XML Parsing and Generation

Published: December 3, 2028
Read time: 5 min read
By: Claude Skills 360

Python’s xml.etree.ElementTree module parses and generates XML using a lightweight tree API. import xml.etree.ElementTree as ET. Parse file: tree = ET.parse("file.xml")ElementTree; root = tree.getroot(). Parse string: root = ET.fromstring(xml_bytes_or_str). Element attributes: el.tag (str), el.text (str|None, text before first child), el.tail (str|None, text after close tag), el.attrib (dict). Find: el.find("tag") → first child or None; el.findall("path") → list; el.findtext("path", default="") → text; el.iter("tag") → all descendants. XPath subset: el.findall("./channel/item"), el.findall(".//{ns}name"), el.findall(".//item[@type='feed']"); namespace maps: {'ns': 'http://...'} passed as second arg to find/findall. Create: el = ET.Element("root", attrib={"id": "1"})ET.SubElement(parent, "child", text="…") creates and appends in one call. Serialize: ET.tostring(el, encoding="unicode", xml_declaration=False). Pretty-print: ET.indent(el). Write to file: tree.write("out.xml", encoding="utf-8", xml_declaration=True). Incremental: ET.iterparse(file, events=("start","end")) for large files. Claude Code generates config readers, RSS parsers, SOAP request builders, sitemap generators, and XML diff tools.

CLAUDE.md for xml.etree.ElementTree

## xml.etree.ElementTree Stack
- Stdlib: import xml.etree.ElementTree as ET
- Parse:  root = ET.fromstring(xml_str)
-         tree = ET.parse("file.xml"); root = tree.getroot()
- Find:   el.find("tag")   el.findall("./channel/item")
-         el.findtext("title", default="")
- Create: root = ET.Element("root")
-         child = ET.SubElement(root, "item", id="1"); child.text = "hello"
- Dump:   ET.indent(root); print(ET.tostring(root, encoding="unicode"))
- Write:  tree.write("out.xml", encoding="utf-8", xml_declaration=True)

xml.etree.ElementTree XML Pipeline

# app/xml_etree_util.py — parse, create, RSS, SOAP, sitemap, diff
from __future__ import annotations

import io
import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from pathlib import Path
from typing import Iterator


# ─────────────────────────────────────────────────────────────────────────────
# 1. Parse helpers
# ─────────────────────────────────────────────────────────────────────────────

def load_xml(source: "str | Path | bytes") -> ET.Element:
    """
    Load XML from a file path, bytes, or string and return the root Element.

    Example:
        root = load_xml("/etc/app/config.xml")
        root = load_xml(b"<root><item>1</item></root>")
    """
    if isinstance(source, (str, Path)):
        return ET.parse(str(source)).getroot()
    return ET.fromstring(source)


def find_text(el: ET.Element, path: str, default: str = "") -> str:
    """
    Return the text of the first element matching path, or default.

    Example:
        title = find_text(channel, "title")
    """
    return el.findtext(path) or default


def iter_elements(root: ET.Element, tag: str) -> Iterator[ET.Element]:
    """
    Yield all descendant elements with the given tag.

    Example:
        for item in iter_elements(root, "item"):
            print(find_text(item, "title"))
    """
    return root.iter(tag)


def attrib(el: ET.Element, name: str, default: str = "") -> str:
    """
    Return attribute value or default.

    Example:
        src = attrib(img_el, "src")
    """
    return el.get(name, default)


# ─────────────────────────────────────────────────────────────────────────────
# 2. Element builder helpers
# ─────────────────────────────────────────────────────────────────────────────

def new_element(tag: str, text: "str | None" = None, **attrs: str) -> ET.Element:
    """
    Create an Element with optional text and attributes.

    Example:
        el = new_element("title", "My Page")
        img = new_element("img", src="logo.png", alt="Logo")
    """
    el = ET.Element(tag, attrib=attrs)
    if text is not None:
        el.text = text
    return el


def append_child(
    parent: ET.Element,
    tag: str,
    text: "str | None" = None,
    **attrs: str,
) -> ET.Element:
    """
    Create a child element, append it to parent, and return it.

    Example:
        item = append_child(channel, "item")
        append_child(item, "title", "Hello World")
        append_child(item, "link", "https://example.com/1")
    """
    child = ET.SubElement(parent, tag, attrib=attrs)
    if text is not None:
        child.text = text
    return child


def to_string(root: ET.Element, indent: bool = True, xml_decl: bool = False) -> str:
    """
    Serialize an Element to a pretty-printed XML string.

    Example:
        print(to_string(root))
    """
    if indent:
        ET.indent(root)
    header = '<?xml version="1.0" encoding="utf-8"?>\n' if xml_decl else ""
    return header + ET.tostring(root, encoding="unicode")


# ─────────────────────────────────────────────────────────────────────────────
# 3. RSS feed parser
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class RssItem:
    title:       str = ""
    link:        str = ""
    description: str = ""
    pub_date:    str = ""
    guid:        str = ""


@dataclass
class RssFeed:
    title:       str = ""
    link:        str = ""
    description: str = ""
    items:       list[RssItem] = field(default_factory=list)


def parse_rss(xml_source: "str | bytes | Path") -> RssFeed:
    """
    Parse an RSS 2.0 feed into an RssFeed dataclass.

    Example:
        feed = parse_rss(urllib.request.urlopen(url).read())
        for item in feed.items[:5]:
            print(item.title, item.link)
    """
    root = load_xml(xml_source)
    channel = root.find("channel") or root
    feed = RssFeed(
        title=find_text(channel, "title"),
        link=find_text(channel, "link"),
        description=find_text(channel, "description"),
    )
    for item_el in channel.findall("item"):
        feed.items.append(RssItem(
            title=find_text(item_el, "title"),
            link=find_text(item_el, "link"),
            description=find_text(item_el, "description"),
            pub_date=find_text(item_el, "pubDate"),
            guid=find_text(item_el, "guid"),
        ))
    return feed


def build_rss(feed: RssFeed) -> str:
    """
    Serialize an RssFeed to an RSS 2.0 XML string.

    Example:
        feed = RssFeed(title="My Blog", link="https://example.com")
        feed.items.append(RssItem(title="Post 1", link="/post/1"))
        print(build_rss(feed))
    """
    rss = ET.Element("rss", version="2.0")
    chan = append_child(rss, "channel")
    append_child(chan, "title", feed.title)
    append_child(chan, "link", feed.link)
    append_child(chan, "description", feed.description)
    for item in feed.items:
        el = append_child(chan, "item")
        append_child(el, "title", item.title)
        append_child(el, "link", item.link)
        if item.description:
            append_child(el, "description", item.description)
        if item.pub_date:
            append_child(el, "pubDate", item.pub_date)
        if item.guid:
            append_child(el, "guid", item.guid)
    return to_string(rss, xml_decl=True)


# ─────────────────────────────────────────────────────────────────────────────
# 4. Namespace-aware utilities
# ─────────────────────────────────────────────────────────────────────────────

def strip_ns(tag: str) -> str:
    """
    Remove the {namespace} prefix from a qualified tag name.

    Example:
        tag = "{http://www.w3.org/2005/Atom}entry"
        print(strip_ns(tag))   # "entry"
    """
    return tag.split("}", 1)[-1] if "}" in tag else tag


def ns_map_from_root(root: ET.Element) -> dict[str, str]:
    """
    Build a prefix→URI namespace map from a root element's tag.
    Useful when the namespace URI is known and you want to build a map.

    Example:
        root = ET.fromstring(atom_xml)
        ns = {"atom": "http://www.w3.org/2005/Atom"}
        for entry in root.findall("atom:entry", ns):
            print(find_text(entry, "atom:title", ns))
    """
    # ET.fromstring doesn't expose prefix; return empty dict for caller to fill
    return {}


def flatten_xml(el: ET.Element, prefix: str = "") -> dict[str, str]:
    """
    Flatten an XML element tree into a dotted-path → text dict.
    Useful for simple config parsing.

    Example:
        data = flatten_xml(ET.fromstring("<cfg><db><host>localhost</host></db></cfg>"))
        # {"cfg.db.host": "localhost"}
    """
    result: dict[str, str] = {}
    tag = strip_ns(el.tag)
    path = f"{prefix}.{tag}" if prefix else tag
    if el.text and el.text.strip():
        result[path] = el.text.strip()
    for child in el:
        result.update(flatten_xml(child, path))
    return result


# ─────────────────────────────────────────────────────────────────────────────
# 5. Sitemap generator
# ─────────────────────────────────────────────────────────────────────────────

_SITEMAP_NS = "http://www.sitemaps.org/schemas/sitemap/0.9"


def build_sitemap(urls: list[dict]) -> str:
    """
    Build an XML sitemap from a list of URL dicts.
    Each dict: {"loc": str, "lastmod": str (optional), "priority": str (optional)}

    Example:
        xml = build_sitemap([
            {"loc": "https://example.com/", "priority": "1.0"},
            {"loc": "https://example.com/about", "lastmod": "2028-12-01"},
        ])
    """
    ET.register_namespace("", _SITEMAP_NS)
    urlset = ET.Element(f"{{{_SITEMAP_NS}}}urlset")
    for u in urls:
        url_el = ET.SubElement(urlset, f"{{{_SITEMAP_NS}}}url")
        ET.SubElement(url_el, f"{{{_SITEMAP_NS}}}loc").text = u["loc"]
        if "lastmod" in u:
            ET.SubElement(url_el, f"{{{_SITEMAP_NS}}}lastmod").text = u["lastmod"]
        if "priority" in u:
            ET.SubElement(url_el, f"{{{_SITEMAP_NS}}}priority").text = u["priority"]
    ET.indent(urlset)
    return '<?xml version="1.0" encoding="UTF-8"?>\n' + ET.tostring(urlset, encoding="unicode")


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

if __name__ == "__main__":
    print("=== xml.etree.ElementTree demo ===")

    # ── parse from string ─────────────────────────────────────────────────────
    print("\n--- load_xml + find_text ---")
    xml_str = b"""<library>
  <book id="1"><title>Python Cookbook</title><author>Beazley</author></book>
  <book id="2"><title>Fluent Python</title><author>Ramalho</author></book>
</library>"""
    root = load_xml(xml_str)
    for book in root.iter("book"):
        bid = attrib(book, "id")
        title = find_text(book, "title")
        author = find_text(book, "author")
        print(f"  id={bid}  title={title!r}  author={author!r}")

    # ── build + to_string ─────────────────────────────────────────────────────
    print("\n--- build element tree ---")
    note = new_element("note")
    append_child(note, "to", "Alice")
    append_child(note, "from", "Bob")
    append_child(note, "body", "Don't forget the xml.etree demo!")
    print(to_string(note))

    # ── flatten_xml ───────────────────────────────────────────────────────────
    print("\n--- flatten_xml ---")
    cfg_xml = b"<config><database><host>localhost</host><port>5432</port></database></config>"
    flat = flatten_xml(load_xml(cfg_xml))
    for k, v in flat.items():
        print(f"  {k} = {v!r}")

    # ── RSS build + parse ─────────────────────────────────────────────────────
    print("\n--- RSS round-trip ---")
    feed = RssFeed(title="Demo Blog", link="https://example.com", description="Test feed")
    feed.items.append(RssItem(title="Hello", link="https://example.com/1", pub_date="Mon, 02 Dec 2028 00:00:00 GMT"))
    feed.items.append(RssItem(title="World", link="https://example.com/2"))
    rss_xml = build_rss(feed)
    parsed = parse_rss(rss_xml.encode())
    print(f"  feed.title: {parsed.title!r}")
    for item in parsed.items:
        print(f"  item: {item.title!r}{item.link!r}")

    # ── sitemap ───────────────────────────────────────────────────────────────
    print("\n--- build_sitemap ---")
    sm = build_sitemap([
        {"loc": "https://example.com/", "priority": "1.0"},
        {"loc": "https://example.com/about", "lastmod": "2028-12-01"},
    ])
    print(sm[:200])

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

For the lxml (PyPI) alternative — lxml.etree offers full XPath 1.0, XSLT, RelaxNG/XML Schema validation, and faster parsing than the stdlib — use lxml when you need full XPath (predicates, axes, functions), schema validation, or performance on very large documents; use xml.etree.ElementTree for zero-dependency XML parsing where the limited XPath subset is sufficient. Note: xml.etree.ElementTree is vulnerable to “billion laughs” and “quadratic blowup” XML attacks on untrusted input — use defusedxml (PyPI) as a safe drop-in replacement when parsing user-supplied XML. For the xmltodict (PyPI) alternative — xmltodict.parse(xml_bytes) converts XML to nested Python dicts and lists in one call — use xmltodict for rapid prototyping when you want to treat XML like JSON without writing a parser subclass; use xml.etree.ElementTree when you need precise control over namespace handling, partial streaming (iterparse), or when you must generate XML output as well as parse it. The Claude Skills 360 bundle includes xml.etree.ElementTree skill sets covering load_xml()/find_text()/iter_elements()/attrib() parse helpers, new_element()/append_child()/to_string() builder utilities, RssFeed/RssItem with parse_rss()/build_rss() RSS round-trip, strip_ns()/flatten_xml() namespace and flatten helpers, and build_sitemap() sitemap XML generator. Start with the free tier to try XML parsing patterns and xml.etree.ElementTree 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