I would like to know why in this code append()
seems to work from inside the loop, but the resulting xml displays the modification from only the last iteration, whi
That's because you only created one instance of <apple/>
to be appended. So basically you just moved that one instance from one parent to another until the last append(sub)
executed. Try to move creation of the <apple/>
element within for
loop instead :
for i, item in enumerate(xml):
sub = etree.fromstring('<apple/>')
item.append(sub)
print('Fruit {} with sub appended: {}'.format(
i, etree.tostring(item).decode('ascii')))
print()
output :
Resulting tree after iterating through items with append():
<tree>
<fruit id="1">
<apple/>
</fruit>
<fruit id="2">
<apple/>
</fruit>
</tree>