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

如何修改XSLT 2.0文件实现从JSON中读取键值生成XML消息?

XSLT读取JSON组装XML的修改方案

核心错误原因

  • XSLT 2.0 原生不支持直接解析JSON输入,默认仅能识别XML格式的输入源,直接传入JSON会导致XSLT无法读取节点值
  • 现有代码存在语法错误:不允许在<xsl:template>标签内部嵌套定义另一个模板,你写在内层的匹配bbbb节点的模板完全不会生效

改造实现

方案1:使用带JSON解析扩展的XSLT处理器(以Saxon为例)

大部分常用的XSLT 2.0实现(如Saxon)都提供了JSON解析扩展函数,你可以将JSON作为字符串参数传入XSLT,解析后再取值,修改后代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
                xmlns:fn="http://www.w3.org/2005/02/xpath-functions"
                xmlns:saxon="http://saxon.sf.net/"
                xmlns:m0="http://services.samples" 
                version="2.0" 
                exclude-result-prefixes="m0 fn saxon">
<xsl:output method="xml" omit-xml-declaration="yes" indent="yes" />
<!-- 传入JSON字符串参数 -->
<xsl:param name="inputJson" />

<xsl:template match="/">
  <!-- 先把JSON转成XML结构 -->
  <xsl:variable name="jsonXml" select="saxon:parse-json($inputJson)" />
  <header>
     <consts>
        <branch>account</branch>
     </consts>
     <message>
        <seo>
           <!-- 直接读取转换后XML里的bbbb节点值 -->
           <xsl:value-of select="$jsonXml//bbbb" />
        </seo>
     </message>
  </header>
</xsl:template>
</xsl:stylesheet>

方案2:通用前置转换方案

如果你的XSLT处理器不支持JSON扩展,可以先将输入JSON转为标准XML结构,示例转换后XML如下:

<root>
  <aaaa>123456</aaaa>
  <bbbb>ENG</bbbb>
  <gen>F</gen>
</root>

对应修改后的XSLT代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
                xmlns:fn="http://www.w3.org/2005/02/xpath-functions"
                xmlns:m0="http://services.samples" 
                version="2.0" 
                exclude-result-prefixes="m0 fn">
<xsl:output method="xml" omit-xml-declaration="yes" indent="yes" />

<xsl:template match="/root">
  <header>
     <consts>
        <branch>account</branch>
     </consts>
     <message>
        <seo>
           <xsl:value-of select="bbbb" />
        </seo>
     </message>
  </header>
</xsl:template>
</xsl:stylesheet>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 06:06:04