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

求助:如何将无属性JSON数组通过XSLT转换为目标结构

XSLT处理JSON数组转换问题

问题场景

需要将嵌套在Body节点下的JSON结构,转换为直接包含name和ids数组的JSON,原XSLT无法正确处理数组导致DataPower报错。

输入JSON

{
  "Body": {
    "name": "jhon",
    "ids": ["a", "b"]
  }
}

期望输出

{
  "name": "jhon",
  "ids": ["a", "b"]
}

原尝试的XSLT及错误

原XSLT代码:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:strip-space elements="*"/>
    <xsl:output method="text"/>
    <xsl:variable name="path" select="*/Body"/>
    <xsl:template match="/">{
        "name" : "<xsl:value-of select="$path/name"/>",
        "ids" : "<xsl:value-of select="$path/ids"/>"
    }
</xsl:template>
</xsl:stylesheet>

执行后DataPower报错,返回:

{
  "Body": {
    "Fault": {
      "faultcode": "",
      "faultactor": "",
      "detail": {
        "IntegrationError": ""
      }
    }
  }
}

移除ids字段后转换正常,说明问题出在数组的处理方式上。

解决方案

原代码直接用<xsl:value-of select="$path/ids"/>会把数组元素拼接成普通字符串,而非合法的JSON数组格式,导致语法错误。需要遍历数组元素,手动构建JSON数组结构:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:strip-space elements="*"/>
    <xsl:output method="text"/>

    <xsl:template match="/">
{
    "name": "<xsl:value-of select="*/Body/name"/>",
    "ids": [
        <xsl:for-each select="*/Body/ids/*">
            "<xsl:value-of select="."/>"<xsl:if test="position() != last()">,</xsl:if>
        </xsl:for-each>
    ]
}
    </xsl:template>
</xsl:stylesheet>

说明

  1. 使用<xsl:for-each>遍历ids数组对应的XML子节点(DataPower会将JSON数组转换为父节点下的多个子元素,比如<string>或<item>)
  2. 每个元素包裹双引号,非最后一个元素后添加逗号,保证JSON语法合法
  3. 若DataPower对JSON数组的XML映射是重复的ids节点(而非子元素),则将select="*/Body/ids/*"改为select="*/Body/ids"即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 11:50:33