如何使用 XPath 选择最后 N 个元素? [英] How do I select the last N elements with XPath?

查看:57
本文介绍了如何使用 XPath 选择最后 N 个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我支持一个网站,该网站生成内容 XML,然后使用 XSLT 将其翻译成网页.我被要求创建一个新的样式表,它将归档"页面的输出转换为 Atom 以进行联合.我遇到的问题是存档页面包含相当多的项目 - 142 个并且还在不断增加 - 并且提要的项目不应超过 30 个.

I support a web site which generates content XML that is then translated into web pages using XSLT. I have been asked to create a new stylesheet which will transform the output of the "archive" page into Atom for syndication. The problem I'm running into is that the archive page contains a rather large number of items — 142 and counting — and the feed should never have more than thirty items.

目前,存档页面的输出如下所示:

Currently, the output from the archive page looks something like this:

<archive>
    <year>
        <month>
            <day>
            <day>
            ...
        </month>

        ...
    </year>

    ...
</archive>

yearmonth 标签由 HTML 转换使用,但与 Atom 提要完全无关.我曾希望将 position() 函数与后代轴一起使用会起作用(//day[position()>last()-30]),但这选择每个月的最后 30 天,这根本不是我需要的.:-)

The year and month tags are used by the HTML transform but are completely irrelevant for an Atom feed. I had hoped that using the position() function with the descendant axis would work (//day[position()>last()-30]), but this selects the last 30 days of each month, which isn't at all what I need. :-)

有没有办法用 XSLT 或 XPath 做到这一点?必须修改 XML 生成器以添加例如 feed="true" 过去三十天的属性似乎是一个非常讨厌的麻烦.

Is there a way to do this with XSLT or XPath? Having to modify the XML generator to add, say, a feed="true" attribute to the last thirty days seems like a pretty nasty kludge.

推荐答案

position()/last() 返回当前上下文中的位置/最后位置,因此当导航器定位在一个 时, position()将返回该月内的 ,而 last() 将返回该月内的最后一个 ,但我想您知道这一点.

position()/last() returns position/last position within the current context, so when the navigator is positioned in one <month>, position() will return <day> within that month, and last() will return last <day> within that month, but i guess you know that.

因此,您可以做的是在选择之前将数组中的所有 展平并放入一个变量中,就像您之前所做的一样.

Therefore, what you could do is flatten all <day>'s in an array and put in a variable, prior to selecting just like you did before.

<xsl:variable name="days" select="//day"/>
<xsl:apply-templates select="$days[position()>last()-30]" />

这篇关于如何使用 XPath 选择最后 N 个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆