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

mariz picture mariz · Jul 1, 2016 · Viewed 33.9k times · Source

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?

Answer

har07 picture har07 · Jul 1, 2016

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(".//*"))