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

在WSO2中通过XSLT仅将ProductId转为字符串的方法

问题描述

我有如下XML payload:

<Product>
<ProductId>790982</ProductId>
<Qty>78</Qty>
</Product>
<Product>
<ProductId>WS-5678</ProductId>
<Qty>34</Qty>
</Product>

(注:原XML中ProductId的闭合标签误写为ReceiptId,已修正)

通过XSLT转换时,用<xsl:value-of select="/ProductId"/>提取值,第一个ProductId会输出数字类型,第二个是字符串类型。我需要只针对ProductId字段统一转为字符串,不想修改synapse-properties做全局转换(会影响所有数字字段)。之前尝试用concat加双引号的方式没生效,代码如下:

<xsl:variable name="quot">"
</xsl:variable>
<xsl:variable name="sku" select="/ProductId"/>
<itemRef>
  <xsl:value-of select="concat($quot, $sku,$quot)"/>
</itemRef>
解决方案

方法1:直接用string()强制转字符串

最简单的方式是用string()函数,不管原节点值是数字还是字符串,直接转为字符串类型,彻底避免类型不一致:

<itemRef>
  <xsl:value-of select="string(ProductId)"/>
</itemRef>

方法2:仅对数字类型的ProductId添加引号

如果需求是数字类型加引号、字符串类型保持原样,可以通过条件判断实现:

<xsl:variable name="quot">"</xsl:variable>
<itemRef>
  <xsl:choose>
    <!-- 判断是否为有效数字:转为数字后不等于NaN即为数字 -->
    <xsl:when test="number(ProductId) != number('NaN')">
      <xsl:value-of select="concat($quot, ProductId, $quot)"/>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="ProductId"/>
    </xsl:otherwise>
  </xsl:choose>
</itemRef>

你之前的concat代码无效,大概率是XPath选择器错误——/ProductId是根节点下的节点,而你的ProductId是Product节点的子节点,在遍历Product的上下文里,应该用ProductId或./ProductId来选择当前节点下的ProductId。

补充:确保遍历上下文正确

如果要处理所有Product节点,需要先遍历节点,确保XPath的上下文正确:

<xsl:template match="/">
  <root>
    <xsl:for-each select="Product">
      <itemRef>
        <xsl:value-of select="string(ProductId)"/>
      </itemRef>
    </xsl:for-each>
  </root>
</xsl:template>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 07:57:48