4

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

0

1 Answer 1

3

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')
Sign up to request clarification or add additional context in comments.

1 Comment

@BartFriederichs yeah, or just a filename string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.