【发布时间】:2017-06-29 16:09:43
【问题描述】:
我正在使用 Python 第三个和 ElementTree API。我有一些 xml 的形式:
<root>
<item>Over the <ref id="river" /> and through the <ref id="woods" />.</item>
<item>To Grandmother's <ref id="house" /> we go.</item>
</root>
我希望能够按顺序遍历给定项目的文本和子节点。所以,对于第一项,我想要逐行打印的列表是:
Over the
<Element 'ref' at 0x######>
and through the
<Element 'ref' at 0x######>
.
但我不知道如何使用 ElementTree 来做到这一点。我可以通过itertext() 和子元素以多种方式按顺序获取文本,但不能将它们按顺序交错在一起。我希望我可以使用像./@text|./ref 这样的XPath 表达式,但是ElementTree 的XPath 子集似乎不支持属性选择。如果我什至可以获取每个项目节点的原始原始 xml 内容,我可以在必要时自己解析出来。
【问题讨论】:
-
最终输出应该如何?
-
输出如上。
标签: python xml xpath elementtree