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

前端 未结 3 2041
终归单人心
终归单人心 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:30

    This is based on the other solutions, but the other solutions did not work in my case (resulted in exceptions) and this one worked:

    from xml.etree import Element, ElementTree
    
    def inner_xml(element: Element):
        return (element.text or '') + ''.join(ElementTree.tostring(e, 'unicode') for e in element)
    

    Use it the same way as in Mark Tolonen's answer.

提交回复
热议问题