fromlxmlimportetreefromioimportStringIOxml='''
data1
data2
data3
data4
data5
data6
'''# this is to simulate that above xml was read from a filefile=StringIO(unicode(xml))# reading the xml from a filetree=etree.parse(file)root=tree.getroot()# iterate over all "b" elementsforelementinroot.iter('b'):# checks if the last "b" element has been reached.# on last element it raises "AttributeError" eception and terminates the for looptry:# attributes of actual elementelem_attrib_ACT=element.attrib# attributes of next elementelem_attrib_NEXT=element.getnext().attribexceptAttributeError:# if no other element, breakbreakprint('attributes of ACTUAL elem:',elem_attrib_ACT,'attributes of NEXT elem:',elem_attrib_NEXT)ifelem_attrib_ACT==elem_attrib_NEXT:print('next elem is duplicate of actual one -> remove it')# I would like to remove next element but this approach is not working# if you uncomment, it removes the elements of "data2" but stops# how to remove the next duplicate element?#element.getparent().remove(element.getnext())else:print('next elem is not a duplicate of actual')print('result:')print(etree.tostring(root))