ElementTree中的非ASCII属性值



我有一个以非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:

如何处理这些属性?

使用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>

最新更新