Python和ElementTree:返回"内部XML",不包括父元素

Jus*_*ant 13 python xml elementtree

在使用ElementTree的Python 2.6中,在特定元素中获取XML(作为字符串)的好方法是什么,比如你在HTML和javascript中可以做什么innerHTML

这是我开始使用的XML节点的简化示例:

<label attr="foo" attr2="bar">This is some text <a href="foo.htm">and a link</a> in embedded HTML</label>
Run Code Online (Sandbox Code Playgroud)

我想最终得到这个字符串:

This is some text <a href="foo.htm">and a link</a> in embedded HTML
Run Code Online (Sandbox Code Playgroud)

我已经尝试迭代父节点并连接子节点tostring(),但这只给了我子节点:

# returns only subnodes (e.g. <a href="foo.htm">and a link</a>)
''.join([et.tostring(sub, encoding="utf-8") for sub in node])
Run Code Online (Sandbox Code Playgroud)

我可以使用正则表达式破解解决方案,但是希望有一些不那么讨厌的东西:

re.sub("</\w+?>\s*?$", "", re.sub("^\s*?<\w*?>", "", et.tostring(node, encoding="utf-8")))
Run Code Online (Sandbox Code Playgroud)

Mar*_*nen 11

怎么样:

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'))
Run Code Online (Sandbox Code Playgroud)

导致:

start here<child1>some text<sub1 />here</child1>and<child2>here as well<sub2 /><sub3 /></child2>end here
here as well<sub2 /><sub3 />
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这仅适用于 Python 2;有关 Python 3 兼容的答案,请参阅下面@JustAC0der 的答案。 (3认同)

Jus*_*der 6

这是基于其他解决方案,但其他解决方案在我的情况下不起作用(导致异常),而这个解决方案有效:

from xml.etree import Element, ElementTree

def inner_xml(element: Element):
    return (element.text or '') + ''.join(ElementTree.tostring(e, 'unicode') for e in element)
Run Code Online (Sandbox Code Playgroud)

使用方法与Mark Tolonen's answer 相同