Parse a small XML settings fixture
Also published in our Blogger archive.
For a compact, controlled XML fixture, xml.etree.ElementTree.fromstring() parses a string directly into its root Element. This example keeps the settings document in memory, finds its direct setting children, and constructs a dictionary from each name attribute and text value. The assertions check the root tag, both decoded settings, and the printed output order.
The fixture represents a small application configuration: theme has the value dark, and retries has the value 3. The list comprehension follows source order, which makes the output deterministic after the dictionary’s insertion order is established. Element.get() retrieves the name attribute and Element.text exposes each element’s text content. The assertions verify this particular fixture and extraction logic; they do not validate a wider configuration schema.
ElementTree is a straightforward tree API, but it is not a schema validator and its supported XPath syntax is intentionally limited. This snippet also assumes the expected direct children exist and contain text. Real configuration handling should decide how to report a missing attribute, duplicate setting name, malformed XML, or non-integer retry value. When parsing untrusted or unauthenticated XML, consult Python’s XML security guidance before treating this convenience API as sufficient for the threat model.
fromstring(), element attributes, and child selection are covered by the Python xml.etree.ElementTree documentation.
AI assistance disclosure: AI helped draft this educational example; its assertions should still be run in the target environment.
import xml.etree.ElementTree as ET
xml_text = """<settings>
<setting name="theme">dark</setting>
<setting name="retries">3</setting>
</settings>"""
root = ET.fromstring(xml_text)
pairs = [(item.get("name"), item.text) for item in root.findall("setting")]
settings = dict(pairs)
assert root.tag == "settings"
assert settings == {"theme": "dark", "retries": "3"}
assert int(settings["retries"]) == 3
print("; ".join(f"{name}={value}" for name, value in pairs))
theme=dark; retries=3