web-dev-qa-db-ja.com

Pythonの要素ツリーで要素の数を見つける方法は?

私は要素ツリーが初めてで、ここでは要素ツリー内の要素の数を見つけようとしています。

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

ルート内の要素の総数を見つける方法はありますか?

13
mariz

すべてのターゲット要素を見つけて(これを行う方法がいくつかあります)、組み込み関数len()を使用してカウントを取得します。たとえば、ルートの直接の子要素のみをカウントする場合:

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

result = len(root.getchildren())

または、ルート要素内のすべての要素をカウントする場合:

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

すべてのノードをリストにロードする必要はありません。sumを使用して遅延反復することができます。

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

サブ要素の数を取得する別の方法:

len(list(root))
5
ThomasW

次のように各要素のカウントを見つけることができます。

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
2
SanD
#  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")
0