【问题标题】:Get Nth child of a node using xpath使用 xpath 获取节点的第 N 个子节点
【发布时间】:2011-01-25 08:28:11
【问题描述】:

我的示例输入 XML 是:

<root>
 <a>
   <b>item</b>
   <b>item1</b>
   <b>item2</b>
   <b>item3</b>
   <b>item4</b>
 </a>
</root>

我想选择一个节点b,它的位置是一个变量的值。

如何使用变量的值来测试节点的位置?

【问题讨论】:

    标签: xml xpath


    【解决方案1】:

    你可以用这个:

    /root/a/b[position()=$variable]
    

    position() 基于 1

    http://saxon.sourceforge.net/saxon6.5.3/expressions.html

    【讨论】:

    • 记住它不是 0-indexed。我只是浪费了 2 个小时在位置 0 上寻找东西。
    【解决方案2】:

    以下应该有效:

    /root/a/b[2]
    

    如果没有,请尝试:

    /root/a/b[position()=2]
    

    【讨论】:

    • 我是来找这两者的区别的,你能解释一下它们有什么不同吗?
    • position() 指 dom 中的位置 [2] 指结果列表中的第二个结果。
    • @Andre。在for-each 循环select 语句中使用时,它们是相同的。当position() 在循环本身中使用时,它指的是结果集。 [n] 格式仅用作速记,因为它是 [ ] 块内的唯一条件,否则必须使用 position(),如 //a[(@id="xx") and (position()=3)],即“任何具有 id 的第五个链接xx"。
    • @Patanjali 这令人困惑 - 与 position() 3 的链接是第 5 个链接?在我看来,[2] 可以用来代替 :nth-of-type(2),而 [position()=2] 则相当于 :nth-child(2)?我想我们需要几个例子来消除迷雾。
    • @Patanjali 我想我已经理解了它是一种速记的部分,因为我已经对其进行了测试,并且它只通过运行\\*[2]\\*[position()=2] 给我“item1”来反对问题XML。谢谢!
    猜你喜欢
    • 2022-10-06
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多