用元素树 python 解析 XML 2.7
parsing XML with element tree python 2.7
为什么我的 for 循环中不接受 i 作为变量?这是我的代码:
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
我得到以下输出:
我要解析的 XML 示例如下:
我正在尝试将文本中的 "count" 加起来。
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)
为什么我的 for 循环中不接受 i 作为变量?这是我的代码:
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
我得到以下输出:
我要解析的 XML 示例如下:
我正在尝试将文本中的 "count" 加起来。
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)