Ich bin neu im Elementbaum, hier versuche ich die Anzahl der Elemente im Elementbaum zu finden.
from lxml import etree
root = etree.parse(open("file.xml",'r'))
gibt es eine Möglichkeit, die Gesamtanzahl der Elemente in root zu ermitteln?
Finden Sie alle Zielelemente (es gibt mehrere Möglichkeiten, dies zu tun) und verwenden Sie dann die integrierte Funktion len()
, um die Anzahl zu ermitteln. Wenn Sie beispielsweise nur direkte untergeordnete Elemente von root zählen möchten:
from lxml import etree
doc = etree.parse("file.xml")
root = doc.getroot()
result = len(root.getchildren())
oder, wenn Sie alle Elemente innerhalb des Wurzelelements zählen möchten:
result = len(root.xpath(".//*"))
Eine andere Möglichkeit, die Anzahl der Unterelemente abzurufen:
len(list(root))
Sie müssen nicht alle Knoten in eine Liste laden. Sie können summenweise und faul durchlaufen:
from lxml import etree
root = etree.parse(open("file.xml",'r'))
count = sum(1 for _ in root.iter("*"))
sie können die Anzahl jedes Elements wie folgt ermitteln:
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
# 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 __== "__main__":
feedDoublePosts("./data/original_appt.xml", "appointment")