如何在python中查找元素树中的元素数量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38138699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find the number of elements in element tree in python?
提问by mariz
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?
有没有办法找到根中元素的总数?
采纳答案by har07
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 :
找到所有目标元素(有一些方法可以做到这一点),然后使用内置函数len()
来获取计数。例如,如果您打算只计算 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(".//*"))
回答by Padraic Cunningham
You don't have to load all the nodes into a list, you can use sum and lazily iterate:
您不必将所有节点加载到列表中,您可以使用 sum 并延迟迭代:
from lxml import etree
root = etree.parse(open("file.xml",'r'))
count = sum(1 for _ in root.iter("*"))
回答by ThomasW
Another way to get the number of subelements:
另一种获取子元素数量的方法:
len(list(root))
回答by SanD
you can find the count of each element like this:
您可以像这样找到每个元素的计数:
from lxml import objectify
file_root = objectify.parse('path/to/file').getroot()
file_root.countchildren() # root's element count
file_root.YourElementName.countchildren() # count of children in any element
回答by Brian Kay Walker
# I used the len(list( )) as a way to get the list of items in a feed, as I
# copy more items I use the original len to break out of a for loop, otherwise
# it would keep going as I add items. Thanks ThomasW for that code.
import xml.etree.ElementTree as ET
def feedDoublePosts(xml_file, item_dup):
tree = ET.ElementTree(file=xml_file)
root = tree.getroot()
for a_post in tree.iter(item_dup):
goround = len(list(a_post))
for post_children in a_post:
if post_children != a_post:
a_post.append(post_children)
goround -= 1
if goround == 0:
break
tree = ET.ElementTree(root)
with open("./data/updated.xml", "w") as f:
tree.write(f)
# ----------------------------------------------------------------------
if __name__ == "__main__":
feedDoublePosts("./data/original_appt.xml", "appointment")