all Python 3xml.etree.ElementTreeterm
xml.etree.ElementTree.ElementTree
tree and elements
A wrapper around a whole document: it holds the root and writes it to a file with write(), with an encoding and an XML declaration.
Syntax
tree = ET.ElementTree(element=None, file=None)
tree.write(file, encoding='us-ascii', xml_declaration=None)
Element models a node, ElementTree a document; only the latter writes files. write() without encoding produces US-ASCII, so Cyrillic turns into П… references; pass encoding='utf-8' and xml_declaration=True if you want a declaration. find/findall/iter on an ElementTree delegate to the root, but a path like '/x' on the tree emits FutureWarning. The module and the class share a name, so do not confuse ET.ElementTree with the module.
Examples
import xml.etree.ElementTree as ET
root = ET.Element('note')
root.text = 'Ж'
tree = ET.ElementTree(root)
tree.write('a.xml')
print(open('a.xml', 'rb').read()) # → b'<note>Ж</note>'
tree.write('u.xml', encoding='utf-8', xml_declaration=True)
print(open('u.xml', encoding='utf-8').read())
# → <?xml version='1.0' encoding='utf-8'?> / <note>Ж</note>
See also
Open in the full glossarydocs.python.orgReport an inaccuracy