mariz mariz - 11 months ago 38
Python Question

How to find the number of elements in element tree in python?

I am new to element tree,here i am trying to find the number of elements in the element tree.

from lxml import etree
root = etree.parse(open("file.xml",'r'))

is there any way to find the total count of the elements in root?


Find all the target elements (there are some ways to do this), and then use built-in function len() to get the count. For example, if you mean to count only direct child elements of root :

from lxml import etree 
doc = etree.parse("file.xml")
root = doc.getroot()

result = len(root.getchildren())

or, if you mean to count all elements within root element :

result = len(root.xpath(".//*"))