在使用 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")))
最佳答案
怎么样:
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 />
关于Python 和 ElementTree : return "inner XML" excluding parent element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3443831/