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

XSLT 3:如何在xsl:evaluate中使用namespace-context

解决Saxon EE 9.9中xsl:evaluate的namespace-context不生效问题

你的问题核心在于:传递给xsl:evaluate的namespace-context参数是文档节点,但该参数要求必须是元素节点——只有元素节点上的命名空间绑定才会被识别为上下文前缀映射。

修正方案

有两种方式可以解决这个问题:

方式1:将namespace-context变量定义为元素节点

通过as="element()"强制变量返回元素节点,而非默认的文档节点:

<xsl:variable name="namespace-context" as="element()">
    <my:dummy xmlns:my="http://example.com/my"/>
</xsl:variable>

方式2:在xsl:evaluate中引用变量的子元素

如果保留原变量定义,只需在参数中指定取变量的子元素(即实际包含命名空间绑定的元素):

<xsl:evaluate xpath="$expr" context-item="$xmlData" namespace-context="$namespace-context/*"/>

完整修正后的测试代码

<xsl:variable name="xmlData">
    <root xmlns="http://example.com/my">
        <element>Hello, World!</element>
    </root>
</xsl:variable>

<xsl:template match="/">
    <xsl:variable name="namespace-context" as="element()">
        <my:dummy xmlns:my="http://example.com/my"/>
    </xsl:variable>
    
    <xsl:variable name="expr" select="'/my:root/my:element'"/>
    <xsl:variable name="result" as="node()*">
        <xsl:evaluate xpath="$expr" context-item="$xmlData" namespace-context="$namespace-context"/>
    </xsl:variable>
    
    <output>
        <xsl:copy-of select="$result"/>
    </output>
</xsl:template>

额外验证点

  1. 确保你确实在使用Saxon EE版本:xsl:evaluate是EE专属特性,HE版本不支持。
  2. 检查XPath路径正确性:你的/my:root/my:element路径是正确的,因为$xmlData作为文档节点,根元素就是<root>(绑定到http://example.com/my命名空间)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 05:43:10