如何从给定的两个输入值生成值的范围(序列)

时间:2014-11-12 11:28:04

标签: xslt

请建议,从两个值生成数字范围。

我使用了调用模板方法。请指教。我正在使用XSLT 2。

XML:

<article>
 <range>3-7</range>
</article>

XSLT:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="//range">
 <xsl:variable name="var1" select="substring-before(., '-')"/>
 <xsl:variable name="var2" select="substring-after(., '-')"/>

 <range>
      <xsl:attribute name="ID">
           <xsl:call-template name="tmpPageRange">
                <xsl:with-param name="stPage" select="$var1"/>
                <xsl:with-param name="lstPage" select="$var2"/>
                <xsl:with-param name="presentvalue" select="$var1"/>
           </xsl:call-template>
      </xsl:attribute>
      <xsl:value-of select="."/>
 </range>
</xsl:template>

      <xsl:template name="tmpPageRange">
           <xsl:param name="stPage"/>
           <xsl:param name="lstPage"/>
           <xsl:param name="presentvalue"/>

           <xsl:if test="number($stPage) &lt; number($lstPage)">
                <xsl:value-of select="concat($presentvalue, ' ')"/>
                <xsl:call-template name="tmpPageRange">
                     <xsl:with-param name="stPage" select="number($stPage) + 1"/>
                     <xsl:with-param name="lstPage"/>
                     <xsl:with-param name="presentvalue" select="$stPage"/>
                </xsl:call-template>
           </xsl:if>
      </xsl:template>
 </xsl:stylesheet>

必需的OutPut:

<range ID="3 4 5 6 7">3-7</range>

2 个答案:

答案 0 :(得分:2)

您可以使用以下内容:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs">
<xsl:template match="article/range">
    <range>
        <xsl:attribute name="ID">
            <xsl:for-each select="xs:integer(tokenize(.,'-')[1]) to xs:integer(tokenize(.,'-')[2])">
                <xsl:value-of select="."/>
                <xsl:if test="position() != last()">
                    <xsl:text> </xsl:text>
                </xsl:if>
            </xsl:for-each>
        </xsl:attribute>
        <xsl:value-of select="."/>
    </range>
</xsl:template>
</xsl:stylesheet>

答案 1 :(得分:2)

Lingamurthy CS's answer之后,XSLT 2.0提供了各种快捷方式,可以让您大大缩短这一点。实际上,根据您的具体要求,您可以直接将其滚动到属性值模板中:

<range ID="{xs:integer(tokenize(.,'-')[1]) to xs:integer(tokenize(.,'-')[2])}">
  <xsl:value-of select="."/>
</range>

AVT中converting a sequence of atomic values to a string的XSLT 2.0规则是将每个项目单独转换为字符串,然后输出由空格分隔的结果序列。如果您想要一个不同的分隔符(或根本没有分隔符),那么您可以使用xsl:attribute,它可以使用separator属性覆盖默认(单个空格)分隔符,例如。

<range>
  <xsl:attribute name="ID"
           select="xs:integer(tokenize(.,'-')[1]) to xs:integer(tokenize(.,'-')[2])"
           separator="," />
  <xsl:value-of select="."/>
</range>

会产生<range ID="3,4,5,6,7">3-7</range>

相关问题