如何使用Python ElementTree获取元素树的所有子元素? [英] How to get all sub-elements of an element tree with Python ElementTree?

查看:837
本文介绍了如何使用Python ElementTree获取元素树的所有子元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到一种方法来获取元素树的所有子元素,就像 ElementTree.getchildren()那样,因为 getchildren()自python 2.7版本以来已被弃用,尽管现在仍可以使用,但我现在不想使用它。

I want to find a way to get all the sub-elements of an element tree like the way ElementTree.getchildren() does, since getchildren() is deprecated since Python version 2.7, I don't want to use it anymore, though I can still use it currently.

谢谢。

推荐答案

elem 的所有子元素(后代):

All sub-elements (descendants) of elem:

all_descendants = list(elem.iter())

一个更完整的示例:

>>> import xml.etree.ElementTree as ET
>>> a = ET.Element('a')
>>> b = ET.SubElement(a, 'b')
>>> c = ET.SubElement(a, 'c')
>>> d = ET.SubElement(a, 'd')
>>> e = ET.SubElement(b, 'e')
>>> f = ET.SubElement(d, 'f')
>>> g = ET.SubElement(d, 'g')
>>> [elem.tag for elem in a.iter()]
['a', 'b', 'e', 'c', 'd', 'f', 'g']

要排除根本身:

>>> [elem.tag for elem in a.iter() if elem is not a]
['b', 'e', 'c', 'd', 'f', 'g']

这篇关于如何使用Python ElementTree获取元素树的所有子元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆