使用XSLT 2.0计算购物车总价值及最贵箱子金额
用XSLT计算购物车总金额与单箱最高金额(Saxon-HE 9.6)
输入XML
<cart> <box> <food type="apple" quantity="3"/> <food type="orange" quantity="2"/> </box> <box> <food type="apple" quantity="6"/> <food type="orange" quantity="1"/> </box> </cart>
解决方案XSLT(兼容XSLT 2.0,适配Saxon-HE 9.6)
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- 定义食物单价 --> <xsl:variable name="apple-price" select="1"/> <xsl:variable name="orange-price" select="2"/> <!-- 计算每个箱子的总金额,生成数值序列 --> <xsl:variable name="box-totals" select=" /cart/box/( sum(food[@type='apple']/@quantity * $apple-price) + sum(food[@type='orange']/@quantity * $orange-price) ) "/> <!-- 购物车总金额 --> <xsl:variable name="cart-total" select="sum($box-totals)"/> <!-- 单个箱子的最高金额 --> <xsl:variable name="max-box-total" select="max($box-totals)"/> <xsl:template match="/"> <result> <cart-total>{$cart-total} 美元</cart-total> <max-box-total>{$max-box-total} 美元</max-box-total> <!-- 示例:用数值变量做xsl:if判断 --> <xsl:if test="$max-box-total > 7"> <note>存在金额超过7美元的箱子</note> </xsl:if> </result> </xsl:template> </xsl:stylesheet>
关键说明
- 直接生成数值变量:无需构建表达式字符串,XSLT 2.0支持在变量中直接完成算术运算与聚合计算。
$box-totals会生成包含每个箱子金额的数值序列(示例中为7, 8)。 - 聚合函数用法:
sum($box-totals)直接求和得到购物车总金额(15美元)。max($box-totals)直接提取序列最大值得到单箱最高金额(8美元)。
- 数值变量用于条件判断:
$max-box-total是数值类型,可直接在xsl:if的test属性中使用,比如示例中判断金额是否超过7美元。
内容的提问来源于stack exchange,提问作者matt73
相关产品推荐
相关产品推荐

