带参数的返回方数列表的XSL函数

时间:2015-12-12 16:46:39

标签: xml xslt

我想要一个带整数参数n的函数,并返回1到n之间整数平方的列表。如果n < 1然后该函数返回空序列。为此,我使用制造商XSL序列。

<xsl:function name="squareNumberList" as="xsd:string">
    <!-- use a param that delimite the list -->
    <xsl:param name="value" as="xsd:decimal *"/>
    <!-- create a sequence of the size of $value and containt 1-2-3-...-value -->
    <xsl:sequence name="seq" select="1 to $value"/>
    <!-- if the value if lesser than 1 return empty sequence -->
    <xsl:if test="value &lt; 1">
        <xsl:value-of select="$value"></xsl:value>
    </xsl:if>
    <!-- calculate 1*1, 2*2, 3*3 ... value*value and store result in res -->
    <xsl:variable name="res" as="xsd:decimal *"> 
        <xsl:for-each select="$seq"> 
            <xsl:sequence select=". * ."/> 
        </xsl:for-each>
    </xsl:variable>
    <!-- return the result -->
    <xsl:value-of select="$res"></xsl:value-of>
</xsl:function>

您能否确认此功能定义明确?

2 个答案:

答案 0 :(得分:2)

你是否认为这比必要的更复杂?一个简单的单行:

<xsl:sequence select="for $i in 1 to $value return $i * $i" />

应该做的。

答案 1 :(得分:1)

XPath 2.0建议已经发布,因为Saxon 9.7(所有版本)支持XPath 3.0,这是使用!的替代方案:

  <xsl:function name="mf:square-list1" as="xs:integer*">
      <xsl:param name="value" as="xs:integer"/>
      <xsl:sequence select="(1 to $value) ! (. * .)"/>
  </xsl:function>

使用高阶函数和for-each与商业版Saxon 9.6 / 7我们也可以使用

  <xsl:function name="mf:square-list2" as="xs:integer*">
      <xsl:param name="value" as="xs:integer"/>
      <xsl:sequence select="for-each(1 to $value, function($n) { $n * $n })"/>
  </xsl:function>