是否可以获取用于评估 xpath 结果的所有上下文节点?

发布于 2024-08-19 06:32:30 字数 720 浏览 4 评论 0原文

是否可以获取用于评估 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,问候

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 ?

TIA, regards

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

于我来说 2024-08-26 06:32:30

我反转了每个阶段的 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

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

半步萧音过轻尘 2024-08-26 06:32:30

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

//particular-element/ancestor::*

例如:

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

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::*
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文