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

如何动态选择XSLT输出格式?遇Map序列化报错问题

动态切换XSLT输出格式时的序列化问题

为实现XSLT输出格式的动态选择,尝试移除顶层<xsl:output>指令,改用<xsl:result-document>指定输出规则,过程中遇到序列化报错,具体情况如下:

原可行代码

原本通过顶层输出指令指定JSON格式,代码运行正常:

<xsl:output method="json" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
    <xsl:variable name="dsl" as="element()">
        <epg lastBuildDate="10/4/2019 9:46:00 AM">
        </epg>
    </xsl:variable>
    <xsl:variable name="output" as="map(*)*">
        <xsl:apply-templates select="$dsl" mode="interpret"/>
    </xsl:variable>
    <xsl:sequence select="$output"/>
</xsl:template>

修改后的代码

移除顶层<xsl:output>,将输出逻辑移入<xsl:result-document>:

<xsl:template match="/">
    <xsl:variable name="dsl" as="element()">
        <epg lastBuildDate="10/4/2019 9:46:00 AM">
        </epg>
    </xsl:variable>
    <xsl:variable name="output" as="map(*)*">
        <xsl:apply-templates select="$dsl" mode="interpret"/>
    </xsl:variable>
    <xsl:result-document method="json" encoding="UTF-8" indent="yes">
        <xsl:sequence select="$output"/>
    </xsl:result-document>
</xsl:template>

报错情况

在Java Saxon 10.6环境中运行修改后的代码时,抛出错误:

cannot serialise a map using this method

后续调整示例代码后恢复正常,但无法明确最初报错的具体原因。

可能的触发因素

结合Saxon 10.x的序列化机制,推测报错可能与以下点相关:

  • 序列化上下文差异:顶层<xsl:output>为整个转换设置默认序列化规则,会自动启用XPath 3.1映射/数组的JSON序列化支持;而<xsl:result-document>作为独立序列化上下文,可能未隐式继承该配置。
  • 类型处理逻辑不同:原代码中直接输出映射变量时,顶层输出的JSON序列化器会自动识别映射类型并转换为对应JSON结构;<xsl:result-document>的序列化器可能因上下文限制,尝试用通用JSON处理逻辑而非专门的序列序列化逻辑。
  • 配置细节遗漏:Saxon对<xsl:result-document>的JSON序列化可能需要显式指定额外参数,以支持映射类型的序列化,而原代码通过顶层输出默认完成了这些配置。

内容的提问来源于stack exchange,提问作者MrD at KookerellaLtd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 09:01:33