我必须使用使用xml.dom.minidom的遗留代码(而且我不能迁移到lxml)。
我想解析这个最小的示例:
<body>
<p>English</p>
<p>Français</p>
</body>以下功能工作得很好:
import codecs
import xml.dom.minidom
def transform1(src_path, dst_path):
tree = xml.dom.minidom.parse(src_path)
# ...
with codecs.open(dst_path, mode="w", encoding="utf-8") as fd:
tree.writexml(fd, encoding="utf-8")但是,如果我改为使用io,那么一切都会出错:
Traceback (most recent call last):
File "/path/to/minidom_demo.py", line 23, in <module>
transform2("sample.xml", "result.xml")
File "/path/to/minidom_demo.py", line 18, in transform2
tree.writexml(fd, encoding="utf-8")
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/minidom.py", line 1747, in writexml
writer.write('<?xml version="1.0" encoding="%s"?>%s' % (encoding, newl))
TypeError: must be unicode, not str如果以二进制模式(mode="wb")打开文件,则会有另一个异常,即:
Traceback (most recent call last):
File "/path/to/minidom_demo.py", line 23, in <module>
transform2("sample.xml", "result.xml")
File "/path/to/minidom_demo.py", line 18, in transform2
tree.writexml(fd, encoding="utf-8")
...
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/minidom.py", line 298, in _write_data
writer.write(data)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 4: ordinal not in range(128)minidom作者似乎不知道Unicode。
为什么它与codecs一起工作?
有办法解决这个问题吗?
发布于 2017-05-30 16:20:02
writexml方法似乎总是转储str。阅读文档告诉我,它的encoding参数只将编码属性添加到XML。
在版本2.3中更改:对于文档节点,可以使用额外的关键字参数编码来指定XML头的编码字段。
你可以试一试:
fd.write(tree.toxml(encoding="utf-8").decode("utf-8"))上面的内容将将XML保存为UTF-8,并在XML头中指定编码。
如果不指定编码,它仍将保存为UTF-8,但编码属性不会包含在标头中。
fd.write(tree.toxml())如果指定编码,但不指定decode(),则会在toxml()返回str时引发异常,这是非常奇怪的。
TypeError: write() argument 1 must be unicode, not strhttps://stackoverflow.com/questions/44254044
复制相似问题