我使用ElementTree
来创建,解析和修改XML文件和对象。我正在创建这样的树:
import xml.etree.ElementTree as etree
foo = etree.Element("root")
etree.SubElement(foo, "extra", { "id": "50" })
然后,我想把它写到一个文件。根据{{3}},我应该使用ElementTree
对象,但是如何从Element
创建它?
我试过
e = etree.ElementTree(foo)
e.write(filename)
但这不起作用:
TypeError:必须是str,而不是bytes
答案 0 :(得分:1)
您打开的文件应使用b
(二进制)标记打开:
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)
或只是将文件名/路径传递给write()
:
e.write('test.xml')