It\'s easy to completely remove a given element from an XML document with lxml\'s implementation of the ElementTree API, but I can\'t see an easy way of consistently replaci
Using strip_elements
has the disadvantage that you cannot make it keep some of the
elements while replacing others. It also requires the existence of an ElementTree
instance (which may be not the case). And last, you cannot use it to replace XML comments or processing instructions.
The following should do your job:
for r in f.xpath('//r'):
text = 'DELETED' + r.tail
parent = r.getparent()
if parent is not None:
previous = r.getprevious()
if previous is not None:
previous.tail = (previous.tail or '') + text
else:
parent.text = (parent.text or '') + text
parent.remove(r)