Simple-Solution Simple-Solution - 5 months ago 9
Python Question

How to get the size/length of sub-elements within an XML tag using python

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

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