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

请求协助:使用XSLT实现指定JSON结构转换及金额计算

XSLT 3.0 实现JSON转换方案

以下是满足你需求的XSLT样式表,需使用支持XSLT 3.0的处理器(如Saxon HE/PE/EE):

<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                exclude-result-prefixes="#all">

  <xsl:output method="json" indent="yes"/>

  <xsl:template match="/">
    <xsl:variable name="input-xml" select="json-to-xml(.)"/>
    <xsl:variable name="line-items" select="$input-xml/*/array[@key='lineLevel']/object"/>
    
    <xsl:map>
      <!-- 保留gp_number字段 -->
      <xsl:map-entry key="'gp_number'" select="$input-xml/*/string[@key='gp_number']/text()"/>
      
      <!-- 重命名数组并添加Amount字段 -->
      <xsl:map-entry key="'AmountCal_line'">
        <xsl:array>
          <xsl:for-each select="$line-items">
            <xsl:variable name="qty" select="number(string[@key='Qty'])"/>
            <xsl:variable name="rate" select="number(string[@key='Rate'])"/>
            <xsl:variable name="amount" select="$qty * $rate"/>
            
            <xsl:object>
              <xsl:copy-of select="string[@key='Qty']"/>
              <xsl:copy-of select="string[@key='Rate']"/>
              <xsl:string key="'Amount'">
                <xsl:value-of select="format-number($amount, '0.00')"/>
              </xsl:string>
            </xsl:object>
          </xsl:for-each>
        </xsl:array>
      </xsl:map-entry>
      
      <!-- 计算TotalAmount -->
      <xsl:map-entry key="'TotalAmount'">
        <xsl:variable name="total" select="sum($line-items/(number(string[@key='Qty']) * number(string[@key='Rate'])))"/>
        <xsl:value-of select="format-number($total, '0.00')"/>
      </xsl:map-entry>
    </xsl:map>
  </xsl:template>

</xsl:stylesheet>

关键逻辑说明

  • 用json-to-xml()将输入JSON转为XML节点,便于XSLT遍历处理
  • 遍历原lineLevel数组元素,把Qty和Rate转为数值后计算乘积,再格式化为两位小数字符串作为Amount字段
  • 通过sum()累加所有元素的乘积,得到TotalAmount
  • 用XSLT的map/array/object结构构建目标JSON,输出时自动转为JSON格式

使用方式

将源JSON作为输入传递给该样式表,通过支持XSLT 3.0的处理器执行转换,即可得到目标JSON。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 14:08:31