You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改XSLT以计算含嵌套productid-6的订单总价

适配特殊产品规则的XSLT 2.0修改方案

需求拆解

  • 兼容常规订单与嵌套结构的变体订单,准确定位productid-6节点
  • 为productid-6实现阶梯定价规则:
    • 订单数量≤5时,固定总价30英镑
    • 订单数量在5-10之间(不含5,含10)时,固定总价60英镑
    • 保留原有常规商品的总价计算逻辑

示例XML结构

常规订单XML

<order>
  <items>
    <item>
      <productid>productid-1</productid>
      <quantity>2</quantity>
      <unitPrice>15</unitPrice>
    </item>
    <item>
      <productid>productid-6</productid>
      <quantity>3</quantity>
      <unitPrice>10</unitPrice>
    </item>
  </items>
</order>

变体订单XML(productid-6嵌套)

<order>
  <items>
    <item>
      <productid>productid-2</productid>
      <quantity>4</quantity>
      <unitPrice>20</unitPrice>
    </item>
    <item>
      <productDetails>
        <productid>productid-6</productid>
        <quantity>7</quantity>
        <unitPrice>10</unitPrice>
      </productDetails>
    </item>
  </items>
</order>

修改后的XSLT 2.0代码

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <!-- 主模板:计算订单总价 -->
  <xsl:template match="/order">
    <orderTotal>
      <total>
        <xsl:value-of select="sum(for $item in items/item return calculate-item-total($item))"/>
      </total>
    </orderTotal>
  </xsl:template>

  <!-- 自定义函数:计算单个商品总价 -->
  <xsl:function name="calculate-item-total" as="xs:decimal">
    <xsl:param name="item" as="element()"/>
    
    <!-- 兼容常规与嵌套结构的节点定位 -->
    <xsl:variable name="productId" select="$item/productid | $item/*/productid"/>
    <xsl:variable name="quantity" select="$item/quantity | $item/*/quantity" as="xs:integer"/>
    <xsl:variable name="unitPrice" select="$item/unitPrice | $item/*/unitPrice" as="xs:decimal"/>

    <xsl:choose>
      <!-- 处理productid-6的特殊定价逻辑 -->
      <xsl:when test="$productId = 'productid-6'">
        <xsl:choose>
          <xsl:when test="$quantity le 5">30</xsl:when>
          <xsl:when test="$quantity gt 5 and $quantity le 10">60</xsl:when>
          <!-- 数量>10时默认按常规单价计算,可按需调整规则 -->
          <xsl:otherwise>
            <xsl:value-of select="$quantity * $unitPrice"/>
          </xsl:otherwise>
        </xsl:choose>
      </xsl:when>
      <!-- 常规商品按单价×数量计算 -->
      <xsl:otherwise>
        <xsl:value-of select="$quantity * $unitPrice"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:function>
</xsl:stylesheet>

关键修改说明

  • 节点兼容:通过$item/productid | $item/*/productid语法,同时匹配常规结构和任意子元素下的productid,同理处理数量、单价节点
  • 阶梯定价:通过双层xsl:choose判断productid-6的数量区间,直接返回对应固定总价
  • 扩展性:预留了数量>10时的处理逻辑,可根据业务需求灵活调整

内容的提问来源于stack exchange,提问作者adam78

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 15:10:08