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

如何用XSLT 1.0将含JSON的XML转换为指定结构的JSON?

用XSLT 1.0实现XML内嵌JSON的结构转换

由于XSLT 1.0没有原生JSON解析能力,只能通过字符串处理函数提取目标字段值,再拼接成新的JSON结构。针对你的需求,以下是可行的实现方案:

完整XSLT代码

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" omit-xml-declaration="yes" indent="no"/>

    <xsl:template match="/root">
        <!-- 提取原始JSON字符串并去除首尾多余空格 -->
        <xsl:variable name="json-text" select="normalize-space(.)"/>
        
        <!-- 提取id字段对应的值 -->
        <xsl:variable name="id-part" select="substring-after($json-text, '&quot;id&quot;:')"/>
        <xsl:variable name="id-value" select="normalize-space(substring-before($id-part, ','))"/>
        
        <!-- 提取country-name字段对应的值 -->
        <xsl:variable name="country-part" select="substring-after($json-text, '&quot;country-name&quot;:')"/>
        <xsl:variable name="country-value" select="normalize-space(substring-before($country-part, '}'))"/>
        
        <!-- 拼接生成目标JSON -->
        <xsl:text>{ &quot;mid&quot;: </xsl:text>
        <xsl:value-of select="$id-value"/>
        <xsl:text>, &quot;cid&quot; : </xsl:text>
        <xsl:value-of select="$country-value"/>
        <xsl:text> }</xsl:text>
    </xsl:template>
</xsl:stylesheet>

代码说明

  • normalize-space(.):清理原始JSON字符串的首尾空格,避免干扰后续截取操作
  • substring-after + substring-before:精准定位目标字段的位置,提取对应的值。该逻辑基于你提供的JSON格式(字段顺序、符号位置)编写,若原始JSON格式有变动(如字段顺序调换、特殊字符转义),需调整截取标记
  • 最后通过<xsl:text>和提取到的变量拼接出符合要求的新JSON结构

测试效果

输入XML:

<root> { "id": 5656, "country-name": "country-text" } </root>

转换后输出:

{ "mid": 5656, "cid" : "country-text" }

局限性说明

该方案仅适配你提供的特定JSON格式,若原始JSON出现以下情况,需调整代码逻辑:

  • 字段顺序发生变化
  • 字段值包含逗号、大括号等特殊字符
  • 存在多余的换行或不规则空格

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 00:12:33