1

With migration to Python 3 xml.etree.ElementTree's write() doesn't work as expected.

I need to make the following code work with Python3:

tree = ET.ElementTree(root)
fileobj = StringIO()

tree.write(fileobj, encoding="utf-8")

The problem with py3 is that it treats fileobj as bytes and therefore fails to write it to StringIO. Then after checking ElementTree docutmentation it appears I have to use encoding='unicode' and this works just fine in py3 but fails with py2.

Now, it there a way to make it work with both py2 and py3 or do I have to use io.BytesIO as a workaround for py3, or shall I use different encoding based on python version?

What is the best solution here?

Nikolay Derkach
  • 1,734
  • 2
  • 22
  • 34

1 Answers1

0

In the end I've decided to use io.BytesIO for both py2 and py3

Nikolay Derkach
  • 1,734
  • 2
  • 22
  • 34