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

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

    How about:

    from xml.etree import ElementTree as ET
    
    xml = 'start heresome texthereandhere as wellend here'
    root = ET.fromstring(xml)
    
    def content(tag):
        return tag.text + ''.join(ET.tostring(e) for e in tag)
    
    print content(root)
    print content(root.find('child2'))
    

    Resulting in:

    start heresome texthereandhere as wellend here
    here as well
    

提交回复
热议问题