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

问题描述:

我正在使用python第三个和ElementTree API。我有一些XML的形式:Python ElementTree - 按顺序遍历子节点和文本

<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()和子元素按顺序获取文本,但不能按顺序将它们交错在一起。我希望我可以使用XPath表达式,如./@text|./ref,但ElementTree的XPath子集似乎不支持属性选择。如果我甚至可以获得每个项目节点的原始XML原始内容,那么我可以根据需要自行解析它。

+0

应该怎么看最后的输出? – RomanPerekhrest

+0

输出如上所述。 – xdhmoore

试试这个:

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 S的 “混合内容” 表示是基于.text.tail属性。元素的.text表示直到第一个子元素的元素文本。那个孩子的.tail然后包含其父母的文本。请参阅API doc