【问题标题】:How to find the number of elements in element tree in python?如何在python中查找元素树中的元素数量?
【发布时间】:2016-11-03 11:16:13
【问题描述】:

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

from lxml import etree 
root = etree.parse(open("file.xml",'r'))

有什么方法可以找到根目录下的元素总数吗?

【问题讨论】:

    标签: python xml lxml elementtree


    【解决方案1】:

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

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

    或者,如果您要计算根元素中的所有元素:

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

    【讨论】:

    • result = len(root.xpath(".//*")) 这正是我要找的......谢谢你,..
    • 不幸的是,getchildren 在 python 2.7 中已被弃用。
    • root.getchildren() -> list(root) 根据文档,您可以简单地执行 len(root)
    【解决方案2】:

    你不必将所有节点加载到一个列表中,你可以使用 sum 和懒惰地迭代:

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

    【讨论】:

    • 这对我来说实际上非常有用,因为我需要计算可能的数千或数万个节点,而且我不想先加载列表中的所有节点。我不确定这是否会导致内存“泄漏”,但为了安全起见,我认为这是一种更安全的方式。你认为这在非​​常大的树上会慢吗?
    【解决方案3】:

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

    len(list(root))
    

    【讨论】:

      【解决方案4】:

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

      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
      

      【讨论】:

        【解决方案5】:
        #  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")
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-11-29
          • 2020-02-12
          • 1970-01-01
          • 1970-01-01
          • 2020-12-09
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多