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.

PythonData Integrity

Code

pythonsnippet
21 lines
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.ElementTree is a Python standard-library module — nothing to install.

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
`xml` — install it with the package manager before running.