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

XSLT3如何将JSON输出改为无键字符串数组?

问题:XSLT转换XML到JSON时生成纯字符串数组的方法

原始XML结构

<cbl:ShippingAddress>
    <cbl:AddressLine AddressLineNumber="1">
        <cbl:Line>line1</cbl:Line>
    </cbl:AddressLine>
    <cbl:AddressLine AddressLineNumber="2">
        <cbl:Line>line2</cbl:Line>
    </cbl:AddressLine>
</cbl:ShippingAddress>

原XSLT代码

<map key="address">
    <array key="lines">
      <xsl:for-each select="/cbl:ShippingAddress/cbl:AddressLine/cbl:Line">
        <map>
          <string key="line">{.}</string>
        </map>
      </xsl:for-each>
    </array>
</map>

当前生成的JSON输出

"lines": [
    {
      "line": "line1"
    },
    {
      "line": "line2"
    }
],

需求

需要将输出改为纯字符串数组形式:

"lines": [
    "line1",
    "line2"
],

遇到的问题

直接将<array key="lines">改为<array>时,出现错误提示:xml-to-json: Child elements of must have a key attribute


解决方案

你只需要修改循环内部的代码,去掉嵌套的<map>和<string>的key属性即可,外层的<array key="lines">必须保留(它对应JSON里的"lines"键):

修改后的XSLT代码:

<map key="address">
    <array key="lines">
      <xsl:for-each select="/cbl:ShippingAddress/cbl:AddressLine/cbl:Line">
        <string>{.}</string>
      </xsl:for-each>
    </array>
</map>

在XML-to-JSON的映射规则里,<array key="lines">对应JSON的"lines": []数组,数组内的<string>元素会直接被序列化为字符串值,而非嵌套对象,这样就能得到你需要的纯字符串数组输出。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 11:40:59