15

在使用 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>

我想以这个字符串结尾:

This is some text <a href="foo.htm">and a link</a> in embedded HTML

我尝试遍历父节点并连接子节点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])

我可以使用正则表达式破解一个解决方案,但希望有比这更简单的东西:

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

3 回答 3

12

怎么样:

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'))

导致:

start here<child1>some text<sub1 />here</child1>and<child2>here as well<sub2 /><sub3 /></child2>end here
here as well<sub2 /><sub3 />
于 2010-08-10T04:34:30.600 回答
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)

使用方式与Mark Tolonen 的回答相同。

于 2018-07-01T16:13:51.280 回答
1

以下对我有用:

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 ''root用于获取元素开头的文本。如果没有文字dom.textNone.

请注意,结果不是有效的 XML - 有效的 XML 应该只有一个根元素。

查看有关混合内容的 ElementTree 文档


使用 Python 2.6.5、Ubuntu 10.04

于 2010-08-09T20:27:04.213 回答