Adding attributes to existing elements, removing elements, etc with lxml

前端 未结 2 1284
一生所求
一生所求 2021-02-14 13:25

I parse in the XML using

from lxml import etree

tree = etree.parse(\'test.xml\', etree.XMLParser())

Now I want to work on the parsed XML. I\'m

2条回答
  •  爱一瞬间的悲伤
    2021-02-14 14:11

    The remove method should do what you want:

    >>> from lxml import etree
    >>> from StringIO import StringIO
    
    >>> s = 'foo'
    >>> tree = etree.parse(StringIO(s))
    
    >>> print(etree.tostring(tree.getroot()))
    foo
    
    >>> title = tree.find('//Title')
    >>> title.getparent().remove(title)
    >>> etree.tostring(tree.getroot())
    ''
    
    >>> print(etree.tostring(tree.getroot()))
    
    

提交回复
热议问题