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

xdh*_*ore 5 python xml xpath elementtree

我正在使用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>
Run Code Online (Sandbox Code Playgroud)

我希望能够依次遍历给定项目的文本和子节点。因此,对于第一个项目,我要逐行打印的列表为:

Over the 
<Element 'ref' at 0x######>
 and through the 
<Element 'ref' at 0x######>
.
Run Code Online (Sandbox Code Playgroud)

但是我不知道如何用ElementTree做到这一点。我可以通过itertext()几种方式按顺序获取文本,通过子元素按顺序获取文本,但不能将它们按顺序交错在一起。我希望可以使用像这样的XPath表达式./@text|./ref,但是ElementTree的XPath子集似乎不支持属性选择。如果我什至可以只获取每个项目节点的原始xml原始内容,则可以在需要时自行解析它。

dns*_*wlt 6

尝试这个:

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)
Run Code Online (Sandbox Code Playgroud)

ElementTree“混合内容”的表示基于.text和.tail属性。该.text元素的表示元素到第一个子元素的文本。那个孩子的.tail然后包含跟随它的父母的文本。请参阅API 文档。