求和所有 xml 个标签值?

Sum all xml tag values?

此代码应该计算此 xml 文档中的评论数。

import urllib
import xml.etree.ElementTree as ET

url = 'http://python-data.dr-chuck.net/comments_42.xml'

print 'Retrieving', url
uh = urllib.urlopen(url)
data = uh.read()
print 'Retrieved',len(data),'characters'
print data
for line in data:
    tree = ET.fromstring(data)
    comments = tree.findall('comments')

    name = comments[0].find('comment').find('name').text
    count = comments[0].find('comment').find('count').text
    count = int(count)
    count = count + count
print count

但它只显示第一个comment标签的评论数,然后将其添加到自己然后停止。

这是输出。顶部是 xml 文档,底部是计数(194,即 97+97,只有评论Romina),这是不正确的。它应该是文件中所有评论的总和,而不仅仅是 Romina 的

如何获取文件中所有评论的总和?

Retrieving http://python-data.dr-chuck.net/comments_42.xml
Retrieved 4189 characters
<?xml version="1.0" encoding="UTF-8"?>
<commentinfo>
  <note>This file contains the sample data for testing</note>

  <comments>
    <comment>
       <name>Romina</name>
       <count>97</count>
    </comment>
    <comment>
       <name>Laurie</name>
       <count>97</count>
    </comment>
    <comment>
       <name>Bayli</name>
       <count>90</count>
    </comment>
    <comment>
       <name>Siyona</name>
       <count>90</count>
    </comment>
    <comment>
       <name>Taisha</name>
       <count>88</count>
    </comment>
    <comment>
       <name>Ameelia</name>
       <count>87</count>
    </comment>
    <comment>
       <name>Alanda</name>
       <count>87</count>
    </comment>
    <comment>
       <name>Prasheeta</name>
       <count>80</count>
    </comment>
</commentinfo>

194

注意细微的变化。 因为 <comments> 包含多个 <comment> 标签,我们首先需要找到所有标签,然后我们才能遍历它们并找到 <count> 标签。

import urllib
import xml.etree.ElementTree as ET

url = 'http://python-data.dr-chuck.net/comments_42.xml'

uh = urllib.urlopen(url)
data = uh.read()

tree = ET.fromstring(data)
comments = tree.find('comments').findall('comment')
total_count = 0
for comment in comments:
    count = comment.find('count').text
    count = int(count)
    total_count += count
print total_count
>> 2553

你的循环逻辑是错误的。而不是

for line in data:
    tree = ET.fromstring(data)
    comments = tree.findall('comments')


    name = comments[0].find('comment').find('name').text
    count = comments[0].find('comment').find('count').text
    count = int(count)
    count = count + count

你需要

tree = ET.fromstring(data)
comments = tree.find('comments').findall('comment')

count = 0
for comment in comments:
    name = comment.find('name').text
    count += int(comment.find('count').text)