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原始內容,那麼我可以根據需要自行解析它。
應該怎麼看最後的輸出? – RomanPerekhrest
輸出如上所述。 – xdhmoore