0

我是 python 的新手,我想知道如何获取父标签中子元素的大小或数量让我们说participants。这个想法是获取标签participant内的数量。participants

这是xml:

<participants>
  <participant>
    <userId>James</userId>
    <role>Author</role>
  </participant>
  <participant>
    <userId>Alex</userId>
    <role>Reader</role>
  </participant>
</participants>

我正在使用 xml:

import xml.etree.ElementTree as ET作为模块

并被ET分配dom = ET.fromstring(output)

到目前为止,为了解析 xml,我编写了以下代码:

for participant in dom.iter('participant'): 
    userId = participant.find('userId').text
    role = participant.find('role').text

但我想获得标签中数量的大小/长度,participantparticipants就是我想要做的,但它没有给我长度:

print 'length', dom.findall('participants').length

我想要的输出应该是:

length 2
4

3 回答 3

4

尝试

print(len(dom.findall('participant')))
于 2013-11-21T08:57:25.910 回答
2

这应该给你长度:

root = tree.getroot()
length = len(root.findall('participant'))
print length
于 2016-06-17T14:59:20.840 回答
1
>>> dom.findall('participant')
[<Element 'participant' at 0x10dd74090>, <Element 'participant' at 0x10dd74250>]
>>> len(dom.findall('participant'))
2
于 2013-11-21T09:00:15.227 回答