【问题标题】:Python XML - Iterate through elements, and if attribute condition is met, append that element with all its children to the listPython XML - 遍历元素,如果满足属性条件,则将该元素及其所有子元素附加到列表中
【发布时间】:2021-12-27 14:30:31
【问题描述】:

我有脚本应该从 XML 文件中过滤掉一些元素。我这样做是因为我确切地知道什么是元素深度,有多少孩子...... 但是你能不能给我一个例子,说明如何在不知道嵌套深度的情况下做到这一点?

代码如下:

def Filter_Modules(folder_name, corresponding_list):
    for element in delta_root.iter('folder'):
      if element.attrib.get('name') == str(folder_name):
        corresponding_list.append(element)
        for child in element:
          corresponding_list.append(child)
          for ch in child:
            corresponding_list.append(ch)
            for c in ch:
              corresponding_list.append(c)

欢迎所有建议..

【问题讨论】:

  • 分享xml(确保它是有效的!)并解释你需要什么。

标签: python xml list nested children


【解决方案1】:

我了解您想输入corresponding_list all folder 元素的后代元素,其中 name 属性等于某个字符串。

那么一个很好的解决方案是使用 recursive 函数。 (在 一般来说,递归是处理数据结构的好方法 树,图表,...)。

递归函数add_sub_tree 追加和elementcorresponding_list 然后递归调用它自己 孩子们。儿童也将附加到corresponding_list 和 该函数将递归调用自身以附加所有孙子 等等。

def Filter_Modules(folder_name, corresponding_list):
    def add_sub_tree(element):
        corresponding_list.append(element)
        for child in element:
            add_sub_tree(child)
        
    for element in delta_root.iter('folder'):
        if element.attrib.get('name') == str(folder_name):
            add_sub_tree(element)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-29
    • 2021-08-26
    • 1970-01-01
    • 2021-11-24
    • 2013-11-15
    • 2015-11-03
    相关资源
    最近更新 更多