使用 xpath 查找倒数第二个节点 [英] find next-to-last node with xpath
问题描述
我有一个带有 chapters
和嵌套的 sections
的 XML 文档.我试图找到任何部分的第一个二级部分祖先.这是 ancestor-or-self
轴中的倒数第二部分.伪代码:
I have a XML document with chapters
and nested sections
.
I am trying to find, for any section, the first second-level section ancestor.
That is the next-to-last section in the ancestor-or-self
axis.
pseudo-code:
<chapter><title>mychapter</title>
<section><title>first</title>
<section><title>second</title>
<more/><stuff/>
</section>
</section>
</chapter>
我的选择器:
<xsl:apply-templates
select="ancestor-or-self::section[last()-1]" mode="title.markup" />
当然在 last()-1 没有定义之前一直有效(当前节点是 first
部分).
Of course that works until last()-1 isn't defined (the current node is the first
section).
如果当前节点低于 second
部分,我想要标题 second
.否则我想要标题first
.
If the current node is below the second
section, i want the title second
.
Otherwise I want the title first
.
推荐答案
用这个替换你的 xpath:
Replace your xpath with this:
ancestor-or-self::section[position()=last()-1 or count(ancestor::section)=0][1]
由于您已经可以在所有情况下找到正确的节点,除了一个,我将您的 xpath 更新为 也 找到 first
部分( 或 count(ancestor::section)=0
),然后选择 ([1]
) 第一个匹配项(以相反的文档顺序,因为我们使用的是 ancestor-or-self
代码>轴).
Since you can already find the right node in all cases except one, I updated your xpath to also find the first
section (or count(ancestor::section)=0
), and then select ([1]
) the first match (in reverse document order, since we are using the ancestor-or-self
axis).
这篇关于使用 xpath 查找倒数第二个节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!