/ / Python ElementTree-子ノードとテキストを順番に繰り返す-python、xml、xpath、elementtree

Python ElementTree - 子ノードとテキストを順番に反復する - python、xml、xpath、elementtree

3番目の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>

特定のアイテムのテキストノードと子ノードを順番に繰り返し処理できるようにしたいと考えています。したがって、最初の項目について、1行ずつ印刷するリストは次のようになります。

Over the
<Element "ref" at 0x######>
and through the
<Element "ref" at 0x######>
.

しかし、ElementTreeでこれを行う方法を理解することはできません。テキストを順番に取得するには、 itertext() 子要素はいくつかの方法で順番に並べられていますが、順番にインターリーブされていません。私は次のようなXPath式を使用できると思っていました ./@text|./ref、しかし、ElementPathのXPathのサブセットは、属性選択をサポートしていないようです。各アイテムノードの元の未加工のxmlコンテンツさえ取得できれば、必要に応じて自分で解析できます。

回答:

回答№1の場合は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「混合コンテンツ」の表現は、 .text そして .tail 属性。の .text 要素のは、最初の子要素までの要素のテキストを表します。あの子 .tail 次に、それに続く親のテキストが含まれます。をご覧ください API doc.