Question

I am using ElementTree to create, parse and modify XML files and object. I am creating the tree like this:

import xml.etree.ElementTree as etree
foo = etree.Element("root")
etree.SubElement(foo, "extra", { "id": "50" })

then, I want to write this to a file. According to the documentation, I should use an ElementTree object for that, but how to create that from the Element?

I tried

e = etree.ElementTree(foo)
e.write(filename)

but that doesn't work:

TypeError: must be str, not bytes

Was it helpful?

Solution

Your opened file should be opened with b (binary) flag:

import xml.etree.ElementTree as etree

foo = etree.Element("root")
etree.SubElement(foo, "extra", { "id": "50" })
e = etree.ElementTree(foo)
with open('test.xml', 'wb') as f:
    e.write(f)

or just pass a filename/path to write():

e.write('test.xml')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top