2013-08-23 65 views
1

所以,我有一个整数数组。我想总结一下。但不是整个数组,而是直到由另一个变量指定的数组中的位置。xslt:总结一个整数数组

例如。此beeing我的数组:

<xsl:variable name="myArray" as="xs:int*"> 
<Item>11</Item> 
<Item>22</Item> 
<Item>33</Item> 
<Item>44</Item> 
<Item>55</Item> 
<Item>66</Item> 
<Item>77</Item> 
<Item>88</Item> 
</xsl:variable> 

这beeing我的位置可变:

<xsl:variable name="myPosition" as="xs:int*">3</xsl:variable> 

我期望结果66. (因为:$ myArray的[1] + $ myArray的[2] + $ myArray的[3] = 11 + 22 + 33 = 66)

听起来很简单,但我找不到解决方案。

我想我需要“总和”功能和“for”和“return”表达式。但我必须承认,并不了解我发现的这些例子和说明。

回答

0

我想你使用的是XSLT 2.0,因为在你的示例中xslt是xlst 1.0中不支持的一些结构。因此,只要您声明Temporary trees,它应该很容易。

我认为你可以用这种方法在应用到任何XML输入<xsl:value-of select="sum($myArray[position() &lt;= $myPosition])" />

+0

是的,我使用XSLT 2.0对不起,不包含此信息!效果很好! – cis

0

此XSL模板应做的工作非常简单。它使用EXSLT扩展功能exlst:node-set将您的变量转换为节点集。

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

    <xsl:variable name="myArray" as="xs:int*"> 
     <Item>11</Item> 
     <Item>22</Item> 
     <Item>33</Item> 
     <Item>44</Item> 
     <Item>55</Item> 
     <Item>66</Item> 
     <Item>77</Item> 
     <Item>88</Item> 
    </xsl:variable> 

    <xsl:variable name="myPosition" as="xs:int*">3</xsl:variable> 

    <!-- Converts the myArray variable (a result-tree fragment) to a node-set and then sums over all those in positions up to and including myPosition value. --> 
    <xsl:template match="/"> 
     <xsl:value-of select="sum(exslt:node-set($myArray)/Item[position() &lt;= $myPosition])"/> 
    </xsl:template> 

</xsl:stylesheet> 

你可以在行动中看到它here