The truth is rarely pure and never simple

python: filtering xml elements

There’s one caveat for iterating over xml.etree elements in python. Although the following code works on iterators – just like in C++ – the code sliently fails in checking consecutive children of the element being iterated over

import xml.etree.ElementTree as ET
xml = ET.parse('filename.xml')
root = xml.getroot()

for elem in root:
    if (elem.get('name') == 'deleteme'):
        root.remove(elem)

The iterator is not invalidated in case an element has been removed. As shuffling the iterators is more the `C way’ of solving problems, the more `pythonic’ solution consists of traversing the list backwards – just like in C++, again.

import xml.etree.ElementTree as ET
xml = ET.parse('filename.xml')
root = xml.getroot()

for elem in reversed(list(root)):
    if (elem.get('name') == 'deleteme'):
        root.remove(elem)