我在 Windows 64 位机器上使用 Python 3.4。
我目前有一个具有多个层次结构的 xml 文件。 xml 树中有许多名为“段落”的元素。但它们可能处于不同的层次结构中。
有什么方法可以简单地计算出这些元素的数量吗?遍历整棵树似乎太耗时了。
最佳答案
如果您要使用 lxml.etree
, 那么您将拥有完整的 XPath 支持并且可以使用 count()
:
import lxml.etree as ET
tree = ET.parse(xml)
paragraphs = tree.xpath('count(//p)')
print(paragraphs)
在xml.etree.ElementTree
你必须通过 findall()
在 Python 中完成它和 len()
因为 limited XPath support :
import xml.etree.ElementTree as ET
tree = ET.parse(xml)
paragraphs = tree.findall('//p')
print(len(paragraphs))
关于python - 有没有一种方法可以使用 Python 计算 xml 文件中某个名称的元素数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37266090/