ElementTree Builds And Serializes XML
Build XML with Element and SubElement, serialize with tostring, pretty-print with indent, then parse it back with fromstring and read values by path lookup.
Code
import xml.etree.ElementTree as ET
# Build the document from Elements: attributes go in the constructor,
# nested content through SubElement
feed = ET.Element('feed', version='1.0')
item = ET.SubElement(feed, 'item', id='42')
ET.SubElement(item, 'title').text = 'Cache warm-up finished'
ET.SubElement(item, 'duration', unit='s').text = '18'
# encoding='unicode' returns a str; 'utf-8' would return bytes
print(ET.tostring(feed, encoding='unicode'))
# indent() adds whitespace so the serialized tree reads clearly
ET.indent(feed, space=' ')
print(ET.tostring(feed, encoding='unicode'))
# Round trip through fromstring and read with path lookups
root = ET.fromstring(ET.tostring(feed))
title = root.find('item/title').text
unit = root.find('item/duration').attrib['unit']
print(title, unit)How the snippet works
The file’s state is a handful of top-level bindings: feed, item, root, title.
Points of care
- No external dependency:
xml.etree.ElementTreeis a Python standard-library module — nothing to install.
Interactive Tools for This Topic
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.XML FormatterRe-indent minified or messy XML into a readable structure, validating that every opening tag has a matching closing tag.XML to JSON ConverterConvert XML to JSON, mapping attributes to @ keys, repeated children to arrays, and text content to #text.
FAQ
- Are there third-party dependencies?
- `xml` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.