将元素写入文件

时间:2014-04-28 13:22:28

标签: python xml elementtree

我使用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

1 个答案:

答案 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')