2010-06-07 29 views
0

我對XSLT的使用時間不太長。我讀過XSLT的變量無法在運行中更新,所以我如何執行以下任務。使用來自XML的XSLT進行動態數據處理

我想總結購買&銷售並將它們放入一個變量,並根據這些值做出一些決定。 (例如,如果購買量大於銷售量,那麼做一些事情,如果沒有,做一些事情)

<rows> 
    <row> 
     <col attr2="Purchase" >100.00</col> 
     <col attr2="Sales" >100.00</col> 
    </row> 
    <row > 
     <col attr2="Purchase" >19.16</col> 
     <col attr2="Sales" >12.94</col> 
    </row> 
    <row > 
     <col attr2="Purchase" >0.67</col> 
     <col attr2="Sales" >2.74</col> 
    </row> 
    <row > 
     <col attr2="Purchase" >71.95</col> 
     <col attr2="Sales" >61.54</col> 
    </row> 
    <row > 
     <col attr2="Purchase" >3.62</col> 
     <col attr2="Sales" >14.72</col> 
    </row> 
    <row > 
     <col attr2="Purchase">8.80</col> 
     <col attr2="Sales">1.22</col> 
    </row> 
    <row > 
     <col attr2="Purchase" >-4.28</col> 
     <col attr2="Sales" >6.53</col> 
    </row> 
</rows> 

如果有人知道,請幫助我。

回答

1

XSL變量是更常量:一旦設置,它們的值不能被改變。更改變量的唯一方法是使用遞歸模板,並使用命名參數來保存當前總和。

或者,如果XSLT沒有sum函數!

<xsl:variable name="$purchase-total" select="sum(col[@attr2='Purchase'])" /> 
<xsl:variable name="$sales-total" select="sum(col[@attr2='Sales'])" /> 
<xsl:choose> 
    <xsl:when test="$purchase-total &gt; $sales-total"> 
     <!-- Do something --> 
    </xsl:when> 
    <xsl:otherwise> 
     <!-- Do something --> 
    </xsl:otherwise> 
</xsl:choose> 
+0

謝謝,快速apply.and它的工作原理。我需要購買和銷售的絕對總和。我無法在這裏使用abs功能? sum(arg(number(col [@ attr2 ='Sales']))) 有沒有其他方法可以使用它。 – Imrul 2010-06-07 07:43:30

+0

'arg()'?你不是指'abs()'嗎?不,我不認爲你可以:'abs()'不返回節點集。爲什麼你想要絕對的總和? – Eric 2010-06-07 08:32:10

+0

對不起!它是abs()。購買/銷售中有'價值。我只需要購買/銷售的ABS價值。那我該怎麼做呢? – Imrul 2010-06-07 08:55:13

0

您可以計算總和,如@Eric的示例所示。

您在您的評論問一個問題:要計算的x絕對值使用以下XPath表達式:

(x > 0)*x - not(x > 0)*x 

例如

隨着所提供的XML文檔,

<xsl:variable name="x" select="(/*/*/col[@attr2='Purchase'])[position()=last()]"/> 

    <xsl:value-of select="($x > 0)*$x - not($x > 0)*$x"/> 

生產

4.28 
+0

感謝您的回覆。你能告訴我這裏會有'x'嗎?我嘗試col [@ attr2 ='Sales']爲'x',但它不起作用。如果你提供一些細節,那麼它會有幫助。 – Imrul 2010-06-10 06:24:06

+0

@Imrul:我已經更新了我的答案,以演示如何使用此XPath表達式的示例。你可能沒有選擇正確的節點 - 輸出這個值來確定你選擇的是什麼。 – 2010-06-10 12:40:52