Python3 中的 ElementTree TypeError "write() argument must be str, not bytes"

ElementTree TypeError "write() argument must be str, not bytes" in Python3

使用 Python3 和 ElementTree 生成 .SVG 文件时遇到问题。

    from xml.etree import ElementTree as et
    doc = et.Element('svg', width='480', height='360', version='1.1', xmlns='http://www.w3.org/2000/svg')

    #Doing things with et and doc

    f = open('sample.svg', 'w')
    f.write('<?xml version=\"1.0\" standalone=\"no\"?>\n')
    f.write('<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n')
    f.write('\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n')
    f.write(et.tostring(doc))
    f.close()

函数 et.tostring(doc) 生成类型错误 "write() argument must be str, not bytes"。我不明白这种行为,"et" 应该将 ElementTree-Element 转换为字符串吗?它适用于 python2,但不适用于 python3。我做错了什么?

尝试:

f.write(et.tostring(doc).decode(encoding))

示例:

f.write(et.tostring(doc).decode("utf-8"))

事实证明,tostring尽管它的名字,实际上确实 return一个对象,其类型是 bytes.

奇怪的事情发生了。无论如何,这是证明:

>>> from xml.etree.ElementTree import ElementTree, tostring
>>> import xml.etree.ElementTree as ET
>>> element = ET.fromstring("<a></a>")
>>> type(tostring(element))
<class 'bytes'>

傻了吧?

幸运的是你可以做到这一点:

>>> type(tostring(element, encoding="unicode"))
<class 'str'>

是的,我们都认为字节是荒谬的,那个古老的、四十多年前的过时编码称为 ascii 已经死了。

别让我开始说他们把 "unicode" 称为 编码 !!!!!!!!!!!!

写入 xml 文件时指定字符串编码。

喜欢 decode(UTF-8)write()。 示例:file.write(etree.tostring(doc).decode(UTF-8))

对我来说,最简单的方法是首先创建一些模板 xml(只需定义根)然后解析它...

docXml = ET.parse('template.xml')
root = docXml.getroot()

然后在我的 xml 中做我想做的事,他们打印出来...

docXml.write("output.xml", encoding="utf-8")

输出文件应该是二进制模式。

f = open('sample.svg', 'wb')