There is an XML of the form:

enter image description here

You need to go around the whole tree and at the end of each branch return the value and the full path to it. The problem is creating a full path. I decided to fill the array with keys, and in the end I would have to merge.

import xmltodict xml_keys = [] xml_keys_temp = [] def foo(obj, parent_key=''): global xml_keys, xml_keys_temp xml_keys.append(parent_key) if isinstance(obj, xmltodict.OrderedDict): for key in obj.keys(): xml_keys_temp.append(key) foo(obj[key], key) xml_keys.clear() else: print(xml_keys, obj) if __name__ == '__main__': with open('18182.xml') as f: xml_file = f.read() foo(xmltodict.parse(xml_file)) 

Output:

 >>> ['', 'Root', 'Data', 'authentication'] true >>> ['', 'Root', 'Data', 'authentication', 'key'] 1234 >>> ['', 'Root', 'Data', 'authentication', 'key', 'method'] book >>> ['book', 'id'] 18182 >>> ['book', 'id', 'title'] A Theory of Fun for Game Design >>> ['book', 'id', 'title', 'is_ebook'] false >>> ['book', 'id', 'title', 'is_ebook', 'work', 'id'] 19639 >>> ['book', 'id', 'title', 'is_ebook', 'work', 'id', 'books_count'] 16 >>> ['average_rating'] 3.94 

    1 answer 1

    Understood. It was necessary to create an xml_list array and, with each recursive call, pass it by argument to the next call, first adding the dictionary key from the previous call, xml_key, to it . At the end of the branch, when the object | = dictionary, create a temporary array full_key_list and add to it all elements of the transferred array + key.

     import xmltodict #Лист с ключами, которые будем передавать дальше xml_list = [] def foo(obj, xml_key='', xml_list_keys = []): # проверяем объект на принадлежность к классу словаря if isinstance(obj, xmltodict.OrderedDict): # добавляем в лист ключ, по которому этот объект получен xml_list.append(xml_key) # по всем ключам в объекте делаем тоже самое for key in obj.keys(): # отдаем в функцию новый объект, ключ и список ключей до него foo(obj[key], key, xml_list) # объект не словарь else: # временный лист для хранения всех ключей full_key_list = [] for key in xml_list: if key: full_key_list.append(key) # добавляем последний ключ full_key_list.append(xml_key) print(full_key_list, obj) if __name__ == '__main__': with open('18182.xml') as f: xml_file = f.read() foo(xmltodict.parse(xml_file)) 

    Output:

     ['Root', 'Data', 'authentication'] true ['Root', 'Data', 'key'] 1234 ['Root', 'Data', 'method'] book ['Root', 'Data', 'book', 'id'] 18182 ['Root', 'Data', 'book', 'title'] A Theory of Fun for Game Design ['Root', 'Data', 'book', 'is_ebook'] false ['Root', 'Data', 'book', 'work', 'id'] 19639 ['Root', 'Data', 'book', 'work', 'books_count'] 16 ['Root', 'Data', 'book', 'work', 'average_rating'] 3.94