The problem: ObjectDictionary.iter('Variable')
actually iterates the whole tree of node ObjectDictionary. The matches of Variable
in your example is 4 level deeper (see the xml dump below).
<Group name="OptionalObjects">
<Array name="Store Parameter Field">
<Index>4112</Index>
<ObjectType>8</ObjectType>
<Variable name="Number of Entries">
<Index>4112</Index>
<Subindex>0</Subindex>
<DataType>5</DataType>
<AccessType>0</AccessType>
<ObjectType>7</ObjectType>
<DefaultValue>3</DefaultValue>
<PDOMapping>0</PDOMapping>
</Variable>
The solution: To remove such elements, you should call Variable.getparent().remove(Variable)
.
As there are many places in your code need to remove elements from an iteration result. I'd suggest define a helper function and call the function to do the job.
def remove_self(target):
target.getparent().remove(target)
# YOUR CODE
for Variable in ObjectDictionary.iter('Variable'):
if Variable.find('./Index').text == str(i):
print 'Variable name: ', Variable.attrib['name']
elif Variable.find('./Index').text != str(i):
remove_self(Variable)