ElementTree の最新バージョン (v1.3 以降) では、簡単に実行できます。
input_element.find('..')
再帰的に。ただし、Python に同梱されている ElementTree にはこの機能がありません。また、Element クラスには上向きのものは何も表示されません。
これは、要素ツリーを徹底的に検索するという難しい方法で行う必要があることを意味すると思います。
def get_ancestors_recursively(e, b):
"Finds ancestors of b in the element tree e."
return _get_ancestors_recursively(e.getroot(), b, [])
def _get_ancestors_recursively(s, b, acc):
"Recursive variant. acc is the built-up list of ancestors so far."
if s == b:
return acc
else:
for child in s.getchildren():
newacc = acc[:]
newacc.append(s)
res = _get_ancestors_recursively(child, b, newacc)
if res is not None:
return res
return None
これは DFS のために遅く、ガベージ コレクションのために大量のリストを生成しますが、それを処理できれば問題ありません。