I have an element that have items and a tag. The element can contain more elements which also have items and a tag, and those elements can also have items and a tag. Beforehand I don’t know how many ‘nested’ elements are in the first element.
I want to save the tag and items in a dictionary with the element as key, and if the element has a ‘nested’ element I want to save that that element and its information in the same dictionary entry as its ‘parent element’.
The code that I have so far works only if the first element has a nested element, and the nested element does not have another nested element in it. This is the code:
def getAllNestedElementInformation(element, nestedDict=None):
infoDict = {'tagName':element.tag}
infoDict.update(getItems(element))
if nestedDict == None:
nestedDict = infoDict
else:
nestedDict['nestedElement'][element] = infoDict
print nestedDict
for nestedElement in element:
nestedDict.update({'nestedElement':collections.defaultdict(dict)})
getAllNestedElementInformation(nestedElement, nestedDict=nestedDict)
I want to have
{'name':'scan', 'nestedElement':{'name':'scanwindow', 'nestedElement':{'name:'cvParam'}}}
but I don’t come further than
{'name':'scan', 'nestedElement':{'name:'scanwindow'}}
because I don’t know how to map the next nestedElement in the the ‘nestedElement’ dict.
To give an example of what I have now and what I want to have, when I print nestedDict I get:
{'index': '0', 'nestedElement': {<Element 'scan' at 0x8068180>: {'tagName': 'scan'}}, 'tagName': 'spectrum', 'id': '1'}
{'index': '0', 'nestedElement': {<Element 'cvParam' at 0x80682a0>: {'name': 'scan start time', 'unitName': 'second', 'tagName': 'cvParam', }}, 'tagName': 'spectrum', 'id': '1'}
And I want to have:
{'index': '0', 'nestedElement': {<Element 'scan' at 0x8068180>: 'tagName': 'scan', 'nestedElement: {'name': 'scan start time', 'unitName': 'second', 'tagName': 'cvParam', }}, 'tagName': 'spectrum', 'id': '1'}
Had to save the return value of getAllNestedElementInformation in a dictionary. Just incase someone want to know: this is what I changed my code into: