我有一个带有非ASCII字符的XML文件作为属性值。像这样的一行:
photo = attributes.find("content[@type='写真']")
让ElementTree抱怨无法比较字符串:
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementPath.py:176:
UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
if elem.get(key) == value:
如何处理这些属性?
答案 0 :(得分:1)
使用Unicode路径表达式:
photo = attributes.find(u"content[@type='写真']")
字符串文字的u
前缀使其成为unicode
对象,不再需要隐式解码。
演示:
>>> from xml.etree import ElementTree as ET
>>> sample = u'''\
... <root>
... <content type="写真">match</content>
... </root>
... '''.encode('utf8')
>>> tree = ET.fromstring(sample)
>>> tree.find("content[@type='写真']")
/.../lib/python2.7/xml/etree/ElementPath.py:176: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
if elem.get(key) == value:
>>> tree.find(u"content[@type='写真']")
<Element 'content' at 0x10690da10>