Home > Back-end >  Python XML - Iterate through elements, and if attribute condition is met, append that element with a
Python XML - Iterate through elements, and if attribute condition is met, append that element with a

Time:12-28

I have script that is supposed to filter out some elements out of XML file. I did it like this because I exactly knew what is depth of element, how many children there are... But can you please give me an example of how this can be done without knowing the depth of nest?

Code looks like this:

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)

All suggestions are welcome..

CodePudding user response:

I understand that you want to put in corresponding_list all descendant elements of the folder element of which the name attribute equals some string.

Then a good solution for that is to use a recursive function. (In general, recursivity is a good approach to handle data structures like trees, graphs, ...).

The recursive function add_sub_tree appends and element to corresponding_list and then recursively calls itself on all its children. Children will also be appended to corresponding_list and the function will recursively call itself to append all grand-children and so on.

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)
  • Related