I wrote the code below to append a XML SubElement, but it is appending the same code twice:
Python Code:
from xml.etree import ElementTree as ET
tree = ET.parse("sample.xml")
root = tree.getroot()
child = parent = ''
NOTFOUND = 0
pos = 0
for user in root:
    Id = user.get("id")
    if Id == '012345':
        for attr in user:
            attr_name = attr.get('name')
            pos = len(user)
            if attr_name != "attrib3" and NOTFOUND != 1:
                print "#1: ", user.get('id'), attr.get('name')
                NOTFOUND = NOTFOUND + 1
                parent = user
                child = attr
                continue
if NOTFOUND == 1:
    newattr = ET.SubElement(parent,'res',attrib={'name':'attrib3'})
    newattr_first_seem = ET.SubElement(newattr, 'first_seem', attrib={'date':'2018-08-01', 'status':'GRANTED'})
    print "#2: ", newattr.attrib
    parent.append(newattr)
tree.write('sample.xml')
Desired output:
<stop>
    <user id="012345">
        <res name="attrib1">
            <first_seem date="2018-07-31" status="REQUESTED" />
            <last_seem date="2018-07-31" status="INPROCESS" />
        </res>
        <res name="attrib2">
            <first_seem date="2018-07-31" status="REQUESTED" />
            <last_seem date="2018-07-31" status="COMPLETED" />
        </res>
        **<res name="attrib3">
            <first_seem date="2018-08-01" status="GRANTED" />
        </res>**        
    </user>
    <user id="123456">
        <res name="attrib1">
            <first_seem date="2018-07-31" status="REQUESTED" />
            <last_seem date="2018-07-31" status="REQUESTED" />
        </res>
    </user>
</stop>
Output created:
<stop>
    <user id="012345">
        <res name="attrib1">
            <first_seem date="2018-07-31" status="REQUESTED" />
            <last_seem date="2018-07-31" status="INPROCESS" />
        </res>
        <res name="attrib2">
            <first_seem date="2018-07-31" status="REQUESTED" />
            <last_seem date="2018-07-31" status="COMPLETED" />
        </res>
        **<res name="attrib3">
            <first_seem date="2018-08-01" status="GRANTED" />
        </res>
        <res name="attrib3">
            <first_seem date="2018-08-01" status="GRANTED" />
        </res>**
    </user>
    <user id="123456">
        <res name="attrib1">
            <first_seem date="2018-07-31" status="REQUESTED" />
            <last_seem date="2018-07-31" status="REQUESTED" />
        </res>
    </user>
</stop>
Could someone help me to figure out why the new SubElement is being record twice? I put the print and the math controls into the if to be sure it is not looping twice (and it is not doing).