![](/img/trans.png)
[英]Is there an elegant way to count tag elements in a xml file using lxml in python?
[英]Is there a way to count the number of elements of a certain name in an xml file using Python?
我在Windows 64位計算機上使用Python 3.4。
我目前有一個xml文件,它有多個層次結構。 xml樹中有許多名稱為“paragraph”的元素。 但他們可能處於不同的等級制度。
有沒有辦法以簡單的方式計算這些元素的數量? 遍歷整棵樹似乎太費時間了。
如果您使用lxml.etree
,那么您將獲得完整的XPath支持並可以使用count()
:
import lxml.etree as ET
tree = ET.parse(xml)
paragraphs = tree.xpath('count(//p)')
print(paragraphs)
在xml.etree.ElementTree
您必須通過findall()
和len()
在Python中執行此操作,因為XPath支持有限 :
import xml.etree.ElementTree as ET
tree = ET.parse(xml)
paragraphs = tree.findall('//p')
print(len(paragraphs))
讀取xml文件並獲取xmlString中的內容。 如果你需要的只是“段落”這個詞的出現次數,你可以這樣做 -
xmlString.count("<paragraph>")
這會對您的xml文件的外觀進行一些假設,並且可能無法在所有情況下使用。
我現在找到了一個簡單的方法來使用xml.dom.minidom
完成這項工作:
import xml.dom.mimidom as DM
tree = DM.parse(xml_file)
paragraphs = tree.getElementByTagName('paragraph')
print(len(paragraphs))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.