XSLT视图数据绑定逻辑在MS XSLT可正常运行,在Saxon引擎报错问题排查
核心报错原因
抛出XPDY0002: The context item for axis step root/customers is absent的根本是全局变量的求值时机与上下文不匹配:
- MS XSLT引擎采用宽松求值策略:会在引擎初始化阶段,就基于初始传入的业务数据文档(也就是包含
根节点的SimpleModel.xml)完成所有全局变量的求值,哪怕后续模板切换到View.xml的文档上下文,已经固化的变量值也能正常被引用。 - Saxon严格遵循XSLT规范实现惰性求值:全局变量的select表达式不会提前固化,只有当变量首次被引用时,才会基于当时的运行上下文执行路径解析。当你的
$customers变量首次在匹配的模板中被引用时,当前上下文已经切换到View.xml的
节点,对应文档的根节点是
,根本不存在 路径,自然抛出上下文缺失的错误。
跨引擎兼容的修正方案
全程保留XSLT 1.0语法,无需调整C#侧的Saxon调用逻辑,仅需两处核心调整即可同时兼容MS XSLT与Saxon:
- 移除依赖隐式根节点的全局变量定义,避免惰性求值时上下文不匹配
- 在模板间通过显式参数传递业务数据集合,不依赖任何隐式上下文路径解析
修正后的完整XSLT实现如下:
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" > <xsl:output method="xml" indent="yes"/> <!-- 匹配初始传入的业务数据根节点 --> <xsl:template match="/customers" priority="1"> <!-- 提前捕获当前上下文下的全部客户记录 --> <xsl:variable name="customerList" select="./customer"/> <!-- 加载视图文档,将客户集合作为参数传入后续流程 --> <xsl:apply-templates select="document('View.xml')"> <xsl:with-param name="customers" select="$customerList"/> </xsl:apply-templates> </xsl:template> <!-- 文档根节点通用入口,透传客户集合参数 --> <xsl:template match="/"> <xsl:param name="customers"/> <xsl:apply-templates select="@* | node()"> <xsl:with-param name="customers" select="$customers"/> </xsl:apply-templates> </xsl:template> <!-- 处理视图中的row节点,为每条客户记录生成对应输出行 --> <xsl:template match="row" priority="1"> <xsl:param name="customers"/> <xsl:variable name="this" select="."/> <xsl:for-each select="$customers"> <xsl:apply-templates select="$this" mode="processRow"> <xsl:with-param name="customer" select="."/> </xsl:apply-templates> </xsl:for-each> </xsl:template> <!-- 处理row内的column节点,从当前客户记录提取字段值填充 --> <xsl:template match="column" mode="processRow"> <xsl:param name="customer"/> <xsl:copy> <xsl:choose> <xsl:when test="@value = 'name'"> <xsl:value-of select="$customer/@name"/> </xsl:when> <xsl:when test="@value = 'id'"> <xsl:value-of select="$customer/@id"/> </xsl:when> </xsl:choose> </xsl:copy> </xsl:template> <!-- processRow模式下的通用节点透传逻辑 --> <xsl:template match="@* | node()" mode="processRow"> <xsl:param name="customer"/> <xsl:copy> <xsl:apply-templates select="@* | node()" mode="processRow"> <xsl:with-param name="customer" select="$customer"/> </xsl:apply-templates> </xsl:copy> </xsl:template> <!-- 默认模式下的身份转换逻辑,全程透传客户集合参数 --> <xsl:template match="@* | node()"> <xsl:param name="customers"/> <xsl:copy> <xsl:apply-templates select="@* | node()"> <xsl:with-param name="customers" select="$customers"/> </xsl:apply-templates> </xsl:copy> </xsl:template> </xsl:stylesheet>
方案说明
- 原有视图盲拷贝的透传逻辑完全保留,视图中所有非row、特殊处理的column节点都会原样输出,不会被修改。
- 所有业务数据引用都通过显式参数传递,完全不依赖隐式上下文节点的路径解析,MS XSLT和Saxon的执行逻辑完全一致,不会出现上下文缺失的报错。
- 全程使用XSLT 1.0语法,无需调整版本兼容性,现有C#侧的Saxon编译、序列化代码可直接复用。
内容的提问来源于stack exchange,提问作者MrD at KookerellaLtd
相关产品推荐
相关产品推荐

