Python Glossary Русский

Python 3.9+xml.etree.ElementTreefunction

xml.etree.ElementTree.indent()

serialization

Adds newlines and indentation to a tree in place so that tostring() and write() produce readable XML. Returns None.

Syntax

ET.indent(tree, space='  ', level=0)

indent() modifies the tree itself, writing whitespace into text and tail, and returns None, so print(ET.indent(root)) prints None. Afterwards text holds runs of whitespace: a trap if the tree is processed further rather than just written out. Existing indentation is overwritten, so calling it twice is safe. Before 3.9 it did not exist, which is why old recipes go through minidom.

Examples

import xml.etree.ElementTree as ET
root = ET.fromstring('<a><b><c/></b></a>')
print(ET.indent(root))  # → None
print(ET.tostring(root, encoding='unicode'))
# → <a> /   <b> /     <c /> /   </b> / </a>
print(repr(root.text))  # → '\n  '

See also

Open in the full glossarydocs.python.orgReport an inaccuracy