Is there a way to count the number of elements of a certain name in an xml file using Python?
Question: I'm using Python 3.4 on a Windows 64-bit machine.

I currently have a xml file which has multiple hierarchies. There are a number
of elements going by the name "paragraph" in the xml tree. But they might be
on different hierarchies.

Is there any way to count the number of these elements in an easy way?
Traversal through the whole tree seems way too time-consuming.


Answer: If you were to use [`lxml.etree`](http://lxml.de/), then you would have a full
XPath support and can use [`count()`](https://developer.mozilla.org/en-
US/docs/Web/XPath/Functions/count):

    
    
    import lxml.etree as ET
    
    tree = ET.parse(xml)
    paragraphs = tree.xpath('count(//p)')
    print(paragraphs)
    

In
[`xml.etree.ElementTree`](https://docs.python.org/3/library/xml.etree.elementtree.html)
you would have to do it in Python via
[`findall()`](https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.findall)
and `len()` because of the [limited XPath
support](https://docs.python.org/3/library/xml.etree.elementtree.html#xpath-
support):

    
    
    import xml.etree.ElementTree as ET
    
    tree = ET.parse(xml)
    paragraphs = tree.findall('//p')
    print(len(paragraphs)) 
    

