如何在python中找到元素树中的元素数量?

时间:2016-07-01 06:41:31

标签: python xml lxml elementtree

我是元素树的新手,在这里我试图找到元素树中元素的数量。

enum {
  IPPROTO_IP = 0,               /* Dummy protocol for TCP               */
#define IPPROTO_IP              IPPROTO_IP
  IPPROTO_ICMP = 1,             /* Internet Control Message Protocol    */
#define IPPROTO_ICMP            IPPROTO_ICMP

有没有办法找到root中元素的总数?

5 个答案:

答案 0 :(得分:12)

找到所有目标元素(有一些方法可以做到这一点),然后使用内置函数len()来计算。例如,如果您只想计算root的直接子元素:

from lxml import etree 
doc = etree.parse("file.xml")
root = doc.getroot()

result = len(root.getchildren())

或者,如果你想计算根元素中的所有元素:

result = len(root.xpath(".//*"))

答案 1 :(得分:5)

您不必将所有节点加载到列表中,您可以使用sum和lazily迭代:

from lxml import etree 
root = etree.parse(open("file.xml",'r'))
count = sum(1 for _ in root.iter("*"))

答案 2 :(得分:4)

获得子元素数量的另一种方法:

len(list(root))

答案 3 :(得分:2)

你可以找到这样的每个元素的数量:

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

答案 4 :(得分:0)

#  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")