xml 解析和 unicode(再次)

xml parsing and unicode (again)

xml header:

<?xml version="1.0" encoding="UTF-8"?><points>

xml 数据片段:

<point>
<id>1781</id><lon>43.245766666667</lon><lat>56.636883333333</lat>
<type>vert</type><last_update>2016-11-18 22:55:11</last_update>
<active>1</active><verified>1</verified><international>0</international><name>Vеrshilovo</name><name_ru>Вершилово</name_ru><city/><belongs>АОН</belongs><inde

代码:

tree = ET.parse(XMLFIL)
root = tree.getroot()
allpoints=root.findall('point')
for point in allpoints:
 id=point.find('id').text
 name=point.find('name').text.encode('utf8')
 print name

这将奖励我 "AttributeError: 'NoneType' object has no attribute 'encode' " 如果我遗漏 'encode' 我会得到臭名昭著的 ''ascii' codec can't encode character u'\u0435' in position 1:序号不在范围内 (128)'

注意错误是 'Vershilovo' 的 'e' :它看起来不错,但是 xml 数据的 hexdump 给出

00000000  56 e5 72 73 68 69 6c 6f  76 6f 0a                 |V.rshilovo.|

我发现了几个相关问题,但 none 给我带来了解决方案。根本原因很可能是我的 xml 数据编码不正确,但我无法控制它。我可以忍受必须将非法值重置为某些默认值,例如“???”等等。

有些商品似乎没有 text 属性。如果 textNone,您可以使用 try-except 块或使用默认值,例如:

name = (point.find('name').text or '').encode('utf8')

另一个例子,使用 if 语句:

name = point.find('name').text
if name: 
    name = name.encode('utf8')