How to grab text from each xml tag when the tags have multiple duplications

KaieKison

New Member
Sorry if the question is obscure but this example xml tells it completely.\[code\]<Components> <Component> <ComponentID>B1</ComponentID> <ComponentName>replace</ComponentName> <Description>replace</Description> </Component> <Component> <ComponentID>D2</ComponentID> <ComponentName>Red</ComponentName> <Description>Red</Description> </Component> <Component> <ComponentID>D3</ComponentID> <ComponentName>Yellow</ComponentName> <Description>Yellow</Description> </Component></Components>\[/code\]Essentially I want to save each of these components to a dictionary. I have tried this code:\[code\]if elem1.tag == 'Components': for elem2 in list(elem1): if elem2.tag == 'Component': temp = 0 for elem3 in list(elem2): if elem3.tag == 'ComponentID': temp+=1 asset['CompID'+str(temp)] = elem3.text for elem3 in list(elem2): if elem3.tag == 'ComponentName': temp+=1 asset['CompName'+str(temp)] = elem3.text for elem3 in list(elem2): if elem3.tag == 'Description': temp+=1 asset['Description'+str(temp)] = elem3.text\[/code\]But the issues that happen is that even though each dictionary key will be unique, it is still only the last found component that information will be obtained.Current output:\[code\]{'CompID1': 'D3', 'CompName2': 'Yellow', 'Description3': 'Yellow'}\[/code\]Desired output:\[code\]{'CompID1': 'B1', 'CompName1': 'replace', 'Description1': 'replace','CompID2': 'D2', 'CompName2': 'Red', 'Description2': 'Red','CompID3': 'D3', 'CompName3': 'Yellow', 'Description3': 'Yellow'}\[/code\]I know my temp calls and allocation may be wrong, but it is the assigning of the text values within each tag that is the main problem as it only finds the last one. The final solution will need dictionaries at the end for use in other methods and functions. So while any tips and solutions are welcomed, if they can be focused on dictionaries that would be very helpful.
 
Back
Top