all Python 3xml.etree.ElementTreefunction
xml.etree.ElementTree.tostringlist()
serialization
Like tostring(), but returns a list of fragments whose concatenation equals the tostring() result. Handy for streaming output.
Syntax
parts = ET.tostringlist(element, encoding='us-ascii', method='xml', *, xml_declaration=None, default_namespace=None, short_empty_elements=True)
The split into fragments is not guaranteed: their number and boundaries are an implementation detail, so never index into the list; the only promise is b''.join(...) == tostring(...). Fragments have the same type as tostring() returns: bytes by default, str with encoding='unicode', so join with b''.join or ''.join accordingly. In everyday code tostring() is enough.
Examples
import xml.etree.ElementTree as ET
e = ET.fromstring('<a><b>1</b></a>')
parts = ET.tostringlist(e)
print(b''.join(parts) == ET.tostring(e)) # → True
print(''.join(ET.tostringlist(e, encoding='unicode'))) # → <a><b>1</b></a>
See also
Open in the full glossarydocs.python.orgReport an inaccuracy