【发布时间】:2013-12-19 19:25:04
【问题描述】:
所以,我正在获取一些 xml 数据。一个这样的例子如下:
xmlString = '<location>san diego, ça</location>'
这目前是一个字符串。我现在需要使用 ElementTree 的 fromstring() 方法将其转换为 XML 对象。 导入如下:
import xml.etree.ElementTree as ET
方法调用为:
xml = ET.fromstring(xmlString)
我不断收到错误,说:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position xxx:
ordinal not in range(128)
为了解决这个问题,我查看了 StackOverflow 以及 Python Docs。
似乎建议对字符串进行编码和解码。
xmlString = xmlString.encode('utf-8', 'ignore')
xmlString = xmlString.decode('ascii', 'ignore')
忽略是针对错误,但它们仍然会出现。这是在将 xmlString 转换为 xml 对象之前完成的。但是仍然出现错误!
有什么想法吗?
完整代码为:
xmlString = '<?xml version="1.0" encoding="UTF-8"?><o><location>san diego, ça</location>
</o>'
xmlString = xmlString.encode('utf-8', 'ignore')
xmlString = xmlString.decode('ascii', 'ignore')
xml = ET.fromstring(xmlString)
使用 Python 2.7
【问题讨论】:
-
是的。分享代码和回溯。
-
@IgnacioVazquez-Abrams 我写了一个可以在命令行中使用的 sn-p
-
XML 通常需要 UTF-8 编码,
fromstring()需要你传入 byte string(不是 unicode)。尝试将 UTF-8 重新编码为 ASCII 是行不通的。 -
@MartijnPieters 但即使我删除了 decode('ascii', 'ignore') 它在对字符串本身进行编码时也会中断
-
这是 Python 2 还是 Python 3?
标签: python xml elementtree non-ascii-characters python-unicode