2013-01-31 39 views
0

我試圖打印總和,但它打印每個值的總和。我想得到總金額。如何在xsl中使用全局變量當我打印總和時,它在xsl中打印楠

作爲一個例子來獲得總和,只需要我們可以編寫sum = sum + value;值就是我們得到的新值和sum已經存在的值。我注意到它總是在xsl中被覆蓋。

這裏是我用

<xsl:template match="Top"> 
    <xsl:if test="position() &lt;= 10"> 


    <xsl:variable name="items" 
      select="/TopHoldings/TopHoldingsEntry 
      [@Type='Company Name||Co||Se||F Weight (%)||Benchmark weight (%)'] 
      [@Date='8/31/2011']" /> 

    <xsl:variable name="totalMarks" 
     select="format-number(substring(substring-after(@Value,'||||'),1,10),'#.#') + 
       format-number(substring(substring-after(@Value,'||||'),1,10),'#.#')"/> 
    <xsl:value-of select="$totalMarks" /> 

    </xsl:if> 
</xsl:template> 

在那裏我有做錯的代碼? XML代碼

<TopHoldings Currency="xxx"> 
      <TopHoldingsEntry Type="CName||C||S||Fund Weight (%)||Benchmark weight (%)" Value="Ab||U||||1.2170000000000||" Date="8/31/2011" /> 
      <TopHoldingsEntry Type="CName||C||S||Fund Weight (%)||Benchmark weight (%)" Value="Acc||I||||1.2170000000000||" Date="7/31/2011" /> 
+0

您可以發佈您輸入XML? –

+0

您在這裏使用XSLT1.0或XSLT2.0嗎? –

回答

0

數字格式

<xsl:variable name="total"> 
    <xsl:value-of select="number(substring(substring-after(@Value,'||||'),1,10))+ 
     number(substring(substring-after(@Value,'||||'),1,10))"/> 
</xsl:variable> 
<xsl:variable name="totalMarks" select="format-number($total,1,10),'#.#')"/> 
+0

沒有格式化,因爲它們是字符串,所以它們不能相加。 – newday

+0

@pottuamman這就是爲什麼添加一個函數號() – vels4j

2

你所想總和=總和+值的事實表明,你正在試圖做到這一點,你會在程序上做到這一點之前執行總和語言,通過編寫一個循環並更改變量的值。那麼,XSLT不是一種程序語言,所以你需要以不同的方式思考。

在XSLT 2.0這簡直是

format-number(
    sum(for $x in TopHoldingsEntry/@Type return number(substring-after('||||'))), 
    ....) 

在XSLT 1.0這是有點困難。我會把它用「兄弟遞歸」這樣做:

<xsl:template match="TopHoldingsEntry"> 
    <xsl:param name="total" select="0"/> 
    <xsl:choose> 
    <xsl:when test="following-sibling::*"> 
     <xsl:apply-templates select="following-sibling::*[1]"> 
     <xsl:with-param name="total" select="$total + number(substring-after(....))"/> 
     </xsl:apply-templates> 
    </xsl:when> 
    <xsl:otherwise> 
     <xsl:value-of select="$total"/> 
    </xsl:otherwise> 
    <xsl:choose> 
</xsl:template> 

再火的過程了與<xsl:apply-templates select="TopHoldingsEntry[1]"/>

+0

following-sibling :: * [1]這是什麼意思? – newday

+0

它獲取上下文節點之後的下一個兄弟元素,即緊跟在父元素後面的元素。 –