有没有办法使用Python计算xml文件中某个名称的元素数量?

joe*_*ong 3 python xml xpath xml-parsing

我在 Windows 64 位机器上使用 Python 3.4。

我目前有一个具有多个层次结构的 xml 文件。在 xml 树中有许多名为“段落”的元素。但它们可能处于不同的层次结构。

有什么方法可以简单地计算这些元素的数量吗?遍历整棵树似乎太耗时了。

ale*_*cxe 5

如果您要使用lxml.etree,那么您将拥有完整的 XPath 支持并且可以使用count()

import lxml.etree as ET

tree = ET.parse(xml)
paragraphs = tree.xpath('count(//p)')
print(paragraphs)
Run Code Online (Sandbox Code Playgroud)

xml.etree.ElementTree你将不得不通过做在Pythonfindall()len()的,因为有限的XPath的支持

import xml.etree.ElementTree as ET

tree = ET.parse(xml)
paragraphs = tree.findall('//p')
print(len(paragraphs)) 
Run Code Online (Sandbox Code Playgroud)