xml.etree.ElementTree — XML trees

xml.etree.ElementTree parsing and serialization on Python 3.13.12, including official limits for untrusted XML, defusedxml as a third-party package, and why tostring is not a semantic canonical form.

模块页正文目前为英文。

xml.etree.ElementTree implements a lightweight XML tree API. Import it as xml.etree.ElementTree; the slug xml-etree-elementtree is only the URL form. The examples parse strings in memory and do not read private files or open network URLs.

The official documentation says: if you need to parse untrusted or unauthenticated data, see XML security. The XML security page describes how attacker-controlled XML can be abused for denial of service, access to local files, network connections, or firewall circumvention. Python's built-in parsers rely on Expat. The same page states that Expat itself does not, by default, access local files or create network connections, and that Expat versions lower than 2.7.2 may be vulnerable to the "billion laughs", "quadratic blowup", and "large tokens" issues. Whether a given Python build uses a bundled or a system Expat depends on how that interpreter was configured; official guidance is to check pyexpat.EXPAT_VERSION. This page does not claim that every Python 3.13 installation is safe, does not construct an exploit, and does not promise that ElementTree is a secure parser for untrusted input.

defusedxml is a third-party package, not part of the standard library. Older Python documentation recommended it as a set of wrappers that can reject DTDs and entities. Current 3.13 docs point to the XML security page rather than shipping that package. defusedxml is also not a drop-in replacement for the full ElementTree API. This reference does not install it and does not treat it as a complete guarantee.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

fromstring, find, and parse errors

fromstring(text) parses an XML string and returns the root Element. find() returns the first matching child or None; findall() returns a list. Element.get() reads an attribute. These helpers use a limited subset of XPath; they are not a general XML Schema validator.

Ill-formed markup raises xml.etree.ElementTree.ParseError, a SyntaxError subclass. The examples below stay with well-formed or obviously mismatched tags and do not include a DTD or entity payload.

fromstring, findall, and ParseError

xml.etree.ElementTree.fromstring(text, parser=None)
Element.find(path, namespaces=None)
Element.findall(path, namespaces=None)
xml.etree.ElementTree.ParseError

fromstring parses an XML string into an Element. Malformed markup raises ParseError. No file or URL is opened here.

ParameterDescription
textXML as a string (or bytes). This example uses a str and does not fetch a document.
parserOptional custom XMLParser. The default parser is used when omitted.
pathA find path such as a child tag name, or a limited XPath subset documented in the official reference.

Returns: fromstring returns the root Element. find returns an Element or None. findall returns a list of elements.

Raises

  • ParseError — Raised when the text is not well-formed XML. The exception carries an error message and a position.
  • This fragment does not parse untrusted input and does not demonstrate entity expansion.
python
import xml.etree.ElementTree as ET

root = ET.fromstring('<box><item id="a">one</item><item id="b">two</item></box>')
print(root.tag)
print([child.get('id') for child in root.findall('item')])
print(root.find('item').text)
try:
    ET.fromstring('<box><item></box>')
except ET.ParseError as exc:
    print(type(exc).__name__)
    print(exc)

Expected output

box
['a', 'b']
one
ParseError
mismatched tag: line 1, column 13

Related: XML diff tool, XML formatter, Official XML security

Official documentation →

Serialization is not a semantic canonical form

tostring(element) serializes a tree. encoding="unicode" returns a str; the default returns bytes. short_empty_elements=True (the default) emits <item /> for an empty element; passing False emits <item></item>. Those strings are different; the tree is the same.

canonicalize() implements C14N 2.0 for the document you give it. It is not a general "same meaning" normalizer. Insignificant-looking whitespace in the input is still part of the parsed tree and can appear in both tostring() and C14N output. Two documents that a human might call equivalent can therefore serialize differently. Ordinary tostring() or write() is not Canonical XML, and this page does not claim a round trip preserves every original spelling of prefixes, declarations, or whitespace.

tostring, short_empty_elements, and canonicalize

xml.etree.ElementTree.tostring(element, encoding=None, method=None, *, xml_declaration=None, default_namespace=None, short_empty_elements=True)
xml.etree.ElementTree.canonicalize(xml_data=None, *, out=None, from_file=None, **options)

Empty-element spelling and whitespace in the input change the serialized text. canonicalize() is C14N 2.0 of that input, not a semantic identity function.

ParameterDescription
elementThe Element to serialize with tostring().
encodingPass "unicode" to get a str. The default returns bytes.
short_empty_elementsIf true (the default), empty elements use the compact <tag /> spelling.
xml_data, from_filecanonicalize() accepts an XML string or a file. This example passes strings only and does not read a user file.

Returns: tostring(..., encoding="unicode") returns a str. canonicalize() returns a str when out is omitted.

  • The pretty and compact inputs are not byte-for-byte equal, and their C14N results stay different because the newlines and spaces are in the tree.
python
import xml.etree.ElementTree as ET

empty = ET.Element('box')
ET.SubElement(empty, 'item')
print(ET.tostring(empty, encoding='unicode'))
print(ET.tostring(empty, encoding='unicode', short_empty_elements=False))

pretty = '<box>\n  <item id="a">one</item>\n</box>'
compact = '<box><item id="a">one</item></box>'
print(ET.tostring(ET.fromstring(pretty), encoding='unicode'))
print(ET.canonicalize(pretty))
print(ET.canonicalize(compact))

Expected output

<box><item /></box>
<box><item></item></box>
<box>
  <item id="a">one</item>
</box>
<box>
  <item id="a">one</item>
</box>
<box><item id="a">one</item></box>

Related: XML formatter, XML diff tool, Official tostring()

Official documentation →