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

使用XSLT 3.0实现XML转JSON时遇映射添加错误求助

问题解决:XSLT 3.0中"Cannot add a map to an XDM node tree"错误

错误原因很明确:你定义的output变量默认会构建XDM节点树,但interpret模板返回的是map类型(属于XDM函数项,并非节点),节点树无法容纳map类型,因此触发该错误。

修复方案

把output变量改成直接持有序列(而非节点树),有两种实现方式:

方式1:用select属性直接获取模板返回值

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    xmlns:map="http://www.w3.org/2005/xpath-functions/map"
    version="3.0">

    <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>
    <!-- 直接通过select获取模板返回的map,跳过节点树构建 -->
    <xsl:variable name="output" as="map(*)" select="apply-templates($dsl, mode='interpret')"/>
    <xsl:sequence select="$output"/>
   </xsl:template>
    
    <xsl:template match="epg" mode="interpret">
        <xsl:sequence select="map { 
            'lastBuildDate' : @lastBuildDate 
            }"/>        
    </xsl:template>
</xsl:stylesheet>

方式2:指定变量类型为可容纳非节点项的类型

<!-- 保留变量内容体,但指定类型为item(),允许容纳map -->
<xsl:variable name="output" as="item()">
    <xsl:apply-templates select="$dsl" mode="interpret"/>
</xsl:variable>

关键改动说明

  • 避免变量默认构建节点树:要么用select直接获取模板返回的序列,要么给变量指定能容纳非节点项的类型(比如item()、map(*))。
  • XSLT 3.0的json输出方法支持直接序列化map和array类型,只要变量持有正确的XDM函数项,就能正常输出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 05:55:16