Start New Discussion within our Software Development Community

I have just figured out how to search for the element that im looking for in a xml file but now when I run it the code loops through i know 3 times maybe even more. I want to know what im missing that would cause it to loop like that. I just need it to run through get the correct information once.

tree = ET.parse(args.destDir + '/' + 'FACTSentered'+args.fileDate+'.xml')
root=tree.getroot()
codeList = root.findall(".//ScanCodes/ScanCode")
code_stats = {}
for el in codeList:
    code = el.find('Code').text
    #print code
    if code != None:
        tree = ET.parse(args.destDir + '/' + 'FACTSentered'+args.fileDate+'.xml')
        root=tree.getroot()
        codeList = root.findall(".//Order/OrderHeader")
        code_stats = {}
        for el in codeList:
            order = el.find('OrderNumber').text
            print order 

You have a nested loop there, and it modifies the list while iterating. That's asking for trouble. You're iterating over codeList and then if code is not None you are modifying codeList. You then iterate over the new codeList, and when it's done goes back to the top of the first loop, which is now confused because it's contents just changed.

Rename the second codeList to something else. You are also shadowing tree and root, but it's not as obvious because they aren't being used after the loop starts. Anyway, rename your variables and if that doesn't help then print(codeList) to make sure you are getting what you think you are getting.

This question has already been answered. Start a new discussion instead.