Python and ElementTree: return “inner XML” excluding parent element

前端 未结 3 2046
终归单人心
终归单人心 2020-12-14 11:15

In Python 2.6 using ElementTree, what\'s a good way to fetch the XML (as a string) inside a particular element, like what you can do in HTML and javascript with innerHTML? <

3条回答
  •  情话喂你
    2020-12-14 11:35

    The following worked for me:

    from xml.etree import ElementTree as etree
    xml = 'start heresome texthereandhere as wellend here'
    dom = etree.XML(xml)
    
    (dom.text or '') + ''.join(map(etree.tostring, dom)) + (dom.tail or '')
    # 'start heresome texthereandhere as wellend here'
    

    dom.text or '' is used to get the text at the start of the root element. If there is no text dom.text is None.

    Note that the result is not a valid XML - a valid XML should have only one root element.

    Have a look at the ElementTree docs about mixed content.


    Using Python 2.6.5, Ubuntu 10.04

提交回复
热议问题