![](/img/trans.png)
[英]How to find element that matches xslt attribute value in for-each loop
[英]How to sum a value in for-each loop in xslt?
XML檔案:
<item>
<item_price>56</item_price>
<gst>10</gst>
</item>
<item>
<item_price>75</item_price>
<gst>10</gst>
</item>
<item>
<item_price>99</item_price>
<gst>10</gst>
</item>
我需要使用XSLT對每個(item_price * gst)求和
我設法通過使用每個循環獲取輸出:
<xsl:for-each select="/item">
<xsl:value-of select="item_price*gst"/>
</xsl:for-each>
我的假設可能與相似,但似乎不起作用:
謝謝你的幫助 :)
根據所使用的XSLT處理器,XSLT 1.0和XSLT 2.0的解決方案有所不同。
XSLT 1.0
對於XSLT 1.0,您需要使用一個遞歸模板,該模板將跟蹤重復的<item>
節點的產品累計值( item_price
* gst
)。
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" />
<xsl:strip-space elements="*" />
<xsl:template match="items">
<sum>
<xsl:call-template name="sumItems">
<xsl:with-param name="nodeSet" select="item" />
</xsl:call-template>
</sum>
</xsl:template>
<xsl:template name="sumItems">
<xsl:param name="nodeSet" />
<xsl:param name="tempSum" select="0" />
<xsl:choose>
<xsl:when test="not($nodeSet)">
<xsl:value-of select="$tempSum" />
</xsl:when>
<xsl:otherwise>
<xsl:variable name="product" select="$nodeSet[1]/item_price * $nodeSet[1]/gst" />
<xsl:call-template name="sumItems">
<xsl:with-param name="nodeSet" select="$nodeSet[position() > 1]" />
<xsl:with-param name="tempSum" select="$tempSum + $product" />
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
XSLT 2.0
在XSLT 2.0的情況下,可以使用sum(item/(item_price * gst))
表達式來計算乘積之和。
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="xml" indent="yes" />
<xsl:strip-space elements="*" />
<xsl:template match="items">
<sum>
<xsl:value-of select="sum(item/(item_price * gst))" />
</sum>
</xsl:template>
</xsl:stylesheet>
在兩種情況下,您的sum
為
<sum>2300</sum>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.