使用元素树python 2.7解析XML

时间:2015-11-12 14:29:06

标签: python xml elementtree

为什么这不接受 i 作为我的for循环中的变量?这是我的代码:

import urllib
import xml.etree.ElementTree as ET

url = 'http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/comments_42.xml'

while True:
    uh = urllib.urlopen(url)
    data = uh.read()
    tree = ET.fromstring(data)

    counts = tree.findall('.//count')
    print "counts[0] = ", counts[0]
    print "counts[0].text = ", counts[0].text
    print "type(int(counts[0].text)) = ", type(int(counts[0].text))
    total = 0
    for i in counts:
        total = total + int(counts[i].text)
    print total
    break

我得到以下输出: enter image description here

我要解析的XML示例如下: enter image description here

我试图在文本中加上“计数”。

1 个答案:

答案 0 :(得分:1)

counts - 是一个元素数组。此处for i in counts: i将是一个元素。你可以写那样的

for elem in counts:
    total += int(elem.text)

for index in range(0, len(counts)):
    total += int(counts[index].text)