gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 01:57:05 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com