【问题标题】:Python ElementTree - iterate through child nodes and text in orderPython ElementTree - 按顺序遍历子节点和文本
【发布时间】: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


【解决方案1】:

试试这个:

from xml.etree import ElementTree as ET

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>"""

root = ET.fromstring(xml)

for item in root:
    if item.text:
        print(item.text)
    for ref in item:
        print(ref)
        if ref.tail:
            print(ref.tail)

ElementTrees 表示“混合内容”基于.text.tail 属性。元素的.text 表示元素的文本,直到第一个子元素。那个孩子的.tail 然后包含它后面的父母的文本。请参阅API doc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多