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

对于第二个结果:

/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 回答