Python Glossary Русский

all Python 3xml.etree.ElementTreefunction

xml.etree.ElementTree.tostring()

serialization

Serializes an element with its whole subtree to XML. By default it returns bytes in US-ASCII; encoding='unicode' gives a str.

Syntax

ET.tostring(element, encoding='us-ascii', method='xml', *, xml_declaration=None, default_namespace=None, short_empty_elements=True)

The classic trap: the result is bytes, so print() shows b'…' and Cyrillic becomes &#1046;. For a str pass encoding='unicode' (exactly that; 'utf-8' still returns bytes). The <?xml…?> declaration is added automatically only for encodings other than us-ascii, utf-8 and unicode; xml_declaration (3.8+) controls it. Since 3.8 attribute order is kept as given; earlier versions sorted it. Call indent() first for pretty output.

Examples

import xml.etree.ElementTree as ET
e = ET.fromstring('<a>Ж</a>')
print(ET.tostring(e))  # → b'<a>&#1046;</a>'
print(ET.tostring(e, encoding='unicode'))  # → <a>Ж</a>
print(type(ET.tostring(e, encoding='utf-8')).__name__)  # → bytes
import xml.etree.ElementTree as ET
e = ET.Element('x', z='1', a='2')
print(ET.tostring(e, encoding='unicode'))  # → <x z="1" a="2" /> — порядок как задан
print(ET.tostring(e, encoding='unicode', short_empty_elements=False))
# → <x z="1" a="2"></x>
print(ET.tostring(ET.fromstring('<p>a<b>b</b>c</p>'), method='text', encoding='unicode'))  # → abc

See also

Open in the full glossarydocs.python.orgReport an inaccuracy