ElementTree 中的非 ASCII 属性值

Non-ASCII attribute values in ElementTree

我有一个 XML 文件,其中包含非 ASCII 字符作为属性值。像这样的一行:

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>