XSL - 元素的和乘法 [英] XSL - sum multiplication of elements
本文介绍了XSL - 元素的和乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有几件像这样的:
<item type="goods">
<quantity unit="pcs">172</quantity>
<unit-price currency="PLN">420</unit-price>
<VAT>7</VAT>
</item>
我想打印这些物品的总成本.那么数学上呢:
I want to print sum of the cost of this items. So what mathematically:
sum(quantity*unit-price)
我怎样才能用 xsl 做到这一点?我尝试使用内部带有 for-each 循环和正常 valye-of 的变量.但我仍然得到一些奇怪的结果(我不会添加这段代码,因为它很糟糕).
How can I do that with xsl? I've tried using variables with for-each loop inside and normal valye-of. but I'm still getting some strange results (I won't add this code since it's just bad).
推荐答案
XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/root">
<xsl:text>sum:</xsl:text>
<xsl:call-template name="sum">
<xsl:with-param name="nodes" select="item"/>
</xsl:call-template>
</xsl:template>
<xsl:template name="sum">
<xsl:param name="nodes" />
<xsl:param name="sum" select="0" />
<xsl:variable name="current" select="$nodes[1]" />
<xsl:if test="$current">
<xsl:call-template name="sum">
<xsl:with-param name="nodes" select="$nodes[position() > 1]" />
<xsl:with-param name="sum" select="$sum + $current/quantity * $current/unit-price" />
</xsl:call-template>
</xsl:if>
<xsl:if test="not($current)">
<xsl:value-of select="$sum" />
</xsl:if>
</xsl:template>
</xsl:stylesheet>
输入 XML:
<root>
<item type="goods">
<quantity unit="pcs">1</quantity>
<unit-price currency="PLN">2</unit-price>
<VAT>7</VAT>
</item>
<item type="goods">
<quantity unit="pcs">10</quantity>
<unit-price currency="PLN">20</unit-price>
<VAT>7</VAT>
</item>
<item type="goods">
<quantity unit="pcs">100</quantity>
<unit-price currency="PLN">200</unit-price>
<VAT>7</VAT>
</item>
</root>
输出:
sum:20202
这篇关于XSL - 元素的和乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文