Domanda

I'm newbie to python and I was wondering how to get the size or number of sub elements within a parent tag lets say participants. The idea is to get the number of participant within participants tag.

Here is the xml:

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

I'm using xml:

import xml.etree.ElementTree as ET as the module

and ET is assigned dom = ET.fromstring(output)

so far, to parse xml, I have written the following code which works:

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

But I want to get the size/length of number of participant in participants tag and this is what I'm trying to do but it doesn't give me the length:

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

The output I want should be:

length 2
È stato utile?

Soluzione 3

>>> dom.findall('participant')
[<Element 'participant' at 0x10dd74090>, <Element 'participant' at 0x10dd74250>]
>>> len(dom.findall('participant'))
2

Altri suggerimenti

try

print(len(dom.findall('participant')))

This should give you the length:

root = tree.getroot()
length = len(root.findall('participant'))
print length
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top