开发者

Is it possible get all context nodes used to evalute xpath result?

开发者 https://www.devze.com 2022-12-18 05:26 出处:网络
Is it possible get all context nodes used to evalute xpath result ? In below code: test_xml = \"\"\" <r>

Is it possible get all context nodes used to evalute xpath result ? In below code:

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)

Result are:

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

Is it possible to get all context nodes used in above xpath evaluation:

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

and for second result:

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

? When using child axis I could get those nodes from working on

element_tree.getpath(elem)

but what abouth other axes ?

开发者_StackOverflow

TIA, regards


I reversed the xpath for each stage to get which items would be evaluated in the result:

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'

gives me:

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

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


If I am understanding your question correctly, you are trying to just get the ancestor nodes of particular nodes. The XPATH expression for this would be:

//particular-element/ancestor::*

such as:

/r/a[2]/b/ancestor::*
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号