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 ?
开发者_StackOverflowTIA, 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::*
精彩评论