1

xpath結果を評価するために使用されるすべてのコンテキストノードを取得することは可能ですか? 以下のコードでは:

test_xml = """
<r>
    <a/>
    <a>
        <b/>
    </a>
    <a>
        <b/>
    </a>
</r>
"""
test_root = lxml.etree.fromstring(test_xml)
res = test_root.xpath("//following-sibling::*[1]/b")
for node in res:
    print test_root.getroottree().getpath(node)

結果は次のとおりです。

/r/a[2]/b
/r/a[3]/b

上記の xpath 評価で使用されるすべてのコンテキスト ノードを取得することは可能ですか。

/r/a[1] /r/a[2] /r/a[2]/b

そして2番目の結果:

/r/a[2] /r/a[3]/b /r/a[3]/b

? 子軸を使用すると、それらのノードが動作しないようにすることができました

element_tree.getpath(elem)

しかし、他の軸はどうですか?

TIAさん、はじめまして

4

2 に答える 2

1

結果でどの項目が評価されるかを取得するために、各ステージの xpath を逆にしました。

for node in res:
    j = node.xpath('./parent::*')[0]
    k = j.xpath('./preceding-sibling::*[1]')[0]
    # You didn't specify these but they were used in the evaluation
    ancestors = k.xpath('./ancestor::*')
    for item in [node, j, k] + ancestors:
        print item.getroottree().getpath(item)
    print '\n\n'

私に与えます:

/r/a[2]/b、/r/a[2]、/r/a[1]、/r

/r/a[3]/b、/r/a[3]、/r/a[2]、/r

于 2011-08-22T23:18:22.480 に答える
0

あなたの質問を正しく理解していれば、特定のノードの祖先ノードを取得しようとしています。このための XPATH 式は次のようになります。

//particular-element/ancestor::*

そのような:

/r/a[2]/b/ancestor::*
于 2010-01-29T17:10:01.447 に答える