2013-08-23 104 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