Python ElementTree - 按顺序遍历子节点和文本

标签 python xml xpath elementtree

我正在使用 python the third 和 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 内容,我可以在必要时自行解析它。

最佳答案

试试这个:

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)

ElementTree 对“混合内容”的表示基于 .text.tail 属性。元素的 .text 代表元素的文本,直到第一个子元素。该子项的 .tail 然后包含其父项的文本。查看API doc .

关于Python ElementTree - 按顺序遍历子节点和文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42174152/

相关文章:

python - 根据列名替换值

python - 插入 MySQL 时出错

python - 绘制直方图,其中 x 轴为索引值,y 轴为每列值的频率

java - 如何将文本文件转换为GPX文件?

php - 用于查找嵌套元素的 Xpath 查询

java - 使用 Xpath 提取属性

python - 如何按周显示数据并显示周数?

javascript - 文档开头不允许使用 XML

java - 如何在 Android 偏好设置中使用 DatePicker

sql - 带有 XMLTABLE 的 Xpath