2017-02-11 41 views
2

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

回答

3

試試這個:

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