是否可以使用所有上下文节点来评估xpath结果?

时间:2010-01-25 15:58:52

标签: python xpath lxml

是否可以使用所有上下文节点来评估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

并获得第二个结果:

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

? 使用子轴时,我可以使这些节点工作

element_tree.getpath(elem)

但是其他轴呢?

TIA,问候

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

如果我正确理解您的问题,您将尝试获取特定节点的祖先节点。 XPATH表达式为:

//particular-element/ancestor::*

如:

/r/a[2]/b/ancestor::*
相关问题