python - 将 unicode 对象传递给 XML 解析器时出现 Unicode 错误

标签 python unicode xml-parsing

我正在尝试读取包含 xml 和 unicode 的 gzip 文件,但出现错误。我使用的代码是:

import gzip
import xml

path = "index.mjml.gz"
gzFile = gzip.open(path, mode='r')
gzContents = gzFile.read()
gzFile.close()

unicodeContents = gzContents.encode('utf-8')
xmlContent = xml.dom.minidom.parseString(unicodeContents)
# Do stuff with xmlContent

当我运行此代码时,出现以下错误(在以 xmlContent 开头的行上失败)

/Library/Frameworks/EPD64.framework/Versions/7.1/lib/python2.7/xml/dom/minidom.pyc in parseString(string, parser)
   1922     if parser is None:
   1923         from xml.dom import expatbuilder
-> 1924         return expatbuilder.parseString(string)
   1925     else:
   1926         from xml.dom import pulldom

/Library/Frameworks/EPD64.framework/Versions/7.1/lib/python2.7/xml/dom/expatbuilder.pyc in parseString(string, namespaces)
    938     else:
    939         builder = ExpatBuilder()
--> 940     return builder.parseString(string)
    941 
    942 

/Library/Frameworks/EPD64.framework/Versions/7.1/lib/python2.7/xml/dom/expatbuilder.pyc in parseString(self, string)
    221         parser = self.getParser()
    222         try:
--> 223             parser.Parse(string, True)
    224             self._setup_subset(string)
    225         except ParseEscape:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 1141336: ordinal not in range(128)

我发现之前有一个类似的答案 Reading utf-8 characters from a gzip file in python ,但我仍然收到错误。

xml解析器有问题吗?

(我使用的是 Python 2.7。?)

最佳答案

您无法将 unicode 字符串传递给 xml.dom.minidom.parseString

它必须是适当编码的字节字符串:

>>> import xml.dom.minidom as xmldom
>>>
>>> source = u"""\
... <?xml version="1.0" encoding="utf-8"?>
... <root><text>Σὲ γνωρίζω ἀπὸ τὴν κόψη</text></root>
... """
>>> doc = xmldom.parseString(source.encode('utf-8'))
>>> print doc.getElementsByTagName('text')[0].toxml()
<text>Σὲ γνωρίζω ἀπὸ τὴν κόψη</text>

编辑

只是为了澄清 - 从 gzipped xml 文件读取的流应直接传递到解析器,而不尝试对其进行编码或解码:

import gzip
import xml

path = "index.mjml.gz"
gzFile = gzip.open(path, mode='r')
gzContents = gzFile.read()
gzFile.close()

xmlContent = xml.dom.minidom.parseString(gzContents)

解析器将从文件开头的 xml 声明中读取编码(如果没有,则假定为“utf-8”)。然后它可以使用它来将内容解码为 un​​icode。

关于python - 将 unicode 对象传递给 XML 解析器时出现 Unicode 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8144131/

相关文章:

java - 不匹配的输入异常 : Cannot deserialize instance of `java.lang.Integer` out of START_OBJECT token

python - 在 GridSearchCV 中明确指定测试/训练集

python - 如何训练神经网络将文本分类为预先存在的类别?

python - 如何断行从函数调用的值

postgresql - Postgresql varchar 计数使用 unicode 字符长度还是 ASCII 字符长度?

unicode - 对 Joel Spolsky 的 Unicode 文章的澄清

python - 如何使用Python将unicode字符串转换为真正的字符串

mysql - Xml To MYSQL 导入使用mysql过程

python - 将绑定(bind)方法传递给函数的奇怪行为

php - 提取 .XSPF 内容