How can one replace an element with text in lxml?

前端 未结 3 2099
礼貌的吻别
礼貌的吻别 2020-12-16 16:32

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

3条回答
  •  执念已碎
    2020-12-16 16:48

    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)
    

提交回复
热议问题