【发布时间】:2016-11-03 11:16:13
【问题描述】:
我是元素树的新手,在这里我试图找到元素树中元素的数量。
from lxml import etree
root = etree.parse(open("file.xml",'r'))
有什么方法可以找到根目录下的元素总数吗?
【问题讨论】:
标签: python xml lxml elementtree
我是元素树的新手,在这里我试图找到元素树中元素的数量。
from lxml import etree
root = etree.parse(open("file.xml",'r'))
有什么方法可以找到根目录下的元素总数吗?
【问题讨论】:
标签: python xml lxml elementtree
找到所有目标元素(有一些方法可以做到这一点),然后使用内置函数len() 来获取计数。例如,如果您的意思是只计算 root 的直接子元素:
from lxml import etree
doc = etree.parse("file.xml")
root = doc.getroot()
result = len(root.getchildren())
或者,如果您要计算根元素中的所有元素:
result = len(root.xpath(".//*"))
【讨论】:
getchildren 在 python 2.7 中已被弃用。
root.getchildren() -> list(root) 根据文档,您可以简单地执行 len(root)
你不必将所有节点加载到一个列表中,你可以使用 sum 和懒惰地迭代:
from lxml import etree
root = etree.parse(open("file.xml",'r'))
count = sum(1 for _ in root.iter("*"))
【讨论】:
另一种获取子元素数量的方法:
len(list(root))
【讨论】:
你可以像这样找到每个元素的计数:
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 __name__ == "__main__":
feedDoublePosts("./data/original_appt.xml", "appointment")
【讨论】: