我必须使用使用^{
我想解析这个最小的示例:
<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
一起工作?你知道吗
有办法解决吗?你知道吗
writexml
方法似乎总是转储str
。阅读文档告诉我,它的encoding
参数只将编码属性添加到XML头中。你知道吗您可以尝试:
上面的代码将XML保存为UTF-8,并在XML头中指定编码。你知道吗
如果不指定编码,它仍将另存为UTF-8,但编码属性不会包含在标头中。你知道吗
如果指定编码,但不
decode()
,它将引发异常,因为toxml()
返回str
,这很奇怪。你知道吗相关问题 更多 >
编程相关推荐