software-mariodiana
9/10/2015 - 2:21 PM

Python 3 presents a wrinkle in printing an XML DOM document, as the data is of type bytes and must be explicitly decoded into a string. Here

Python 3 presents a wrinkle in printing an XML DOM document, as the data is of type bytes and must be explicitly decoded into a string. Here, we build an example DOM document and print it to STDOUT.

import io

# Note: xml.etree.cElementTree has been deprecated.
from xml.etree.ElementTree import Element, ElementTree

foo = Element('foo')
bar = Element('bar')
bar.text = 'baz'

foo.append(bar)

doc = ElementTree(foo)

b = io.BytesIO()
doc.write(b)

print(b.getvalue().decode('utf-8'))

"""
<foo><bar>baz</bar></foo>
"""