Python ElementTree - 按顺序遍历子节点和文本
Python ElementTree - iterate through child nodes and text in order
我正在使用 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 内容,我可以在必要时自行解析它。
试试这个:
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
对 "mixed content" 的表示基于 .text
和 .tail
属性。元素的 .text
代表元素的文本,直到第一个子元素。该子项的 .tail
然后包含其父项的文本。见 API doc.
我正在使用 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 内容,我可以在必要时自行解析它。
试试这个:
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
对 "mixed content" 的表示基于 .text
和 .tail
属性。元素的 .text
代表元素的文本,直到第一个子元素。该子项的 .tail
然后包含其父项的文本。见 API doc.