Python 和 ElementTree : return "inner XML" excluding parent element

标签 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>

我想以这个字符串结束:

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/

相关文章:

python - FastAPI 删除调用的 API 响应

Python 将 DLL 复制到 Windows 上的站点包

python - 允许使用 token `class` 作为方法签名中的命名参数

java - 无法使用 FlowTextView 设置文本大小

JAVA - 如何使用 StAX 基于子节点从 xml 中删除父节点

使用 ElementTree 解析 Python XML 返回 None

python - Scikit-learn:我的线性回归不是直线,它很乱

xml - 如何在 WSO2 Integration 上将自闭标签 xml 转换为空标签 xml

python - 使用 ElementTree 解析带有命名空间的 XML 字符串

python - 使用带有标签的 ElementTree 从 XML 检索文本时遇到问题