You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在XSL中按范围显示XML的指定row节点?

解决方案

方法1:固定范围筛选(显示第3到第8个节点)

如果需求是固定展示第3至第8个<row>节点,直接用position()函数做位置判断即可:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="/root">
        <root>
            <!-- 筛选位置在3到8之间的row节点 -->
            <xsl:apply-templates select="row[position() >= 3 and position() <= 8]"/>
        </root>
    </xsl:template>

    <xsl:template match="row">
        <xsl:copy-of select="."/>
    </xsl:template>
</xsl:stylesheet>

方法2:动态范围筛选(排除前2行和后2行)

如果需要根据总行数动态排除首尾各2行(不管总共有多少个<row>),结合count()函数计算总行数来筛选:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="/root">
        <root>
            <!-- 统计所有row节点的总数 -->
            <xsl:variable name="totalRows" select="count(row)"/>
            <!-- 筛选位置大于2,且小于等于(总数-2)的节点 -->
            <xsl:apply-templates select="row[position() > 2 and position() <= $totalRows - 2]"/>
        </root>
    </xsl:template>

    <xsl:template match="row">
        <xsl:copy-of select="."/>
    </xsl:template>
</xsl:stylesheet>

关键说明

  • position():返回当前节点在同级节点中的位置,从1开始计数。
  • count(row):统计<root>下所有<row>节点的总数量。
  • 两种方法按需选择:第一种适合固定范围的场景,第二种可以灵活调整排除的首尾行数(比如要排除前3行后3行,只需把代码中的数字2替换为3)。

内容的提问来源于stack exchange,提问作者karl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 09:25:11