There is an XML of the form:
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 