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

前端 未结 3 2028
终归单人心
终归单人心 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 = '<root>start here<child1>some text<sub1/>here</child1>and<child2>here as well<sub2/><sub3/></child2>end here</root>'
    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 here<child1>some text<sub1 />here</child1>and<child2>here as well<sub2 /><sub3 /></child2>end here
    here as well<sub2 /><sub3 />
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-14 11:35

    The following worked for me:

    from xml.etree import ElementTree as etree
    xml = '<root>start here<child1>some text<sub1/>here</child1>and<child2>here as well<sub2/><sub3/></child2>end here</root>'
    dom = etree.XML(xml)
    
    (dom.text or '') + ''.join(map(etree.tostring, dom)) + (dom.tail or '')
    # 'start here<child1>some text<sub1 />here</child1>and<child2>here as well<sub2 /><sub3 /></child2>end 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

    0 讨论(0)
提交回复
热议问题