2

「get_ancestors_recursively」関数が必要です。
サンプル実行は次のようになります

>>> dump(tr)
<anc1>
  <anc2>
    <element> </element>
  </anc2>
</anc1>
>>> input_element = tr.getiterator("element")[0]
>>> get_ancestors_recursively(input_element)
['anc1', 'anc2']

誰かがこれを手伝ってくれますか?

4

3 に答える 3

3

もう 1 つのオプションは、組み込みの ElementTree API に便利な拡張機能を提供するLXMLです。外部モジュールをインストールする場合は、Element.getparent()に到達するまで単純に再帰的に呼び出すことができる便利な関数がありますElementTree.getroot()。これはおそらく最も高速で最も洗練されたソリューションです (ツリー全体で適切なペアlxml.etree moduleを検索する代わりに、親を指す要素のポインター属性を導入するため)。parent/child

于 2010-06-17T17:54:00.740 に答える
2

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 のために遅く、ガベージ コレクションのために大量のリストを生成しますが、それを処理できれば問題ありません。

于 2010-06-14T22:41:57.463 に答える