无法在XSLT 2.0中的匹配XPath表达式中使用模板参数?
根据SO问题,应该可以在XPath表达式中使用参数进行匹配。但是,如果xsl:template的xsl:param要在同一个模板中使用,则它似乎不起作用 我的XML文件如下所示无法在XSLT 2.0中的匹配XPath表达式中使用模板参数?,xslt,xslt-2.0,Xslt,Xslt 2.0,根据SO问题,应该可以在XPath表达式中使用参数进行匹配。但是,如果xsl:template的xsl:param要在同一个模板中使用,则它似乎不起作用 我的XML文件如下所示 <?xml version="1.0" encoding="UTF-8"?> <myRoot> <myNode myAttribute="3"> <myChildAttribute myChildAttribute="a" /> </m
<?xml version="1.0" encoding="UTF-8"?>
<myRoot>
<myNode myAttribute="3">
<myChildAttribute myChildAttribute="a" />
</myNode>
<myNode myAttribute="2">
<myChildAttribute myChildAttribute="b" />
</myNode>
<myNode myAttribute="1" />
</myRoot>
是否不能在同一模板的匹配XPath表达式中使用模板的参数 我认为这行不通。参数在您定义的模板内有效。但是,匹配表达式实际上不是模板的一部分。当myParam尚未定义时,必须从外部对其进行评估 您必须将maxmyNode/@myAttribute的筛选移动到apply templates调用的select表达式 是否无法在中使用模板的参数 匹配同一模板的XPath表达式 否,选择执行模板时,模板匹配表达式中的任何变量/参数都必须在定义的范围内/可见 因为模板是在全局级别定义的XSLT指令,所以它们可以看到的范围内的唯一变量/参数是全局级别的变量/参数 模板的参数仅在选择执行模板后传递给它,而不是在此之前。这意味着在执行模板选择过程时,此参数的值不存在 因此,如果要在执行过程的模板选择中使用非全局表达式,则需要在相应的xsl:apply templates指令的select属性中提供该表达式,其中可以计算该表达式,而不是在模板的match属性中,其中无法计算该表达式 为了说明这一点,以下代码更正了所提供代码中的问题:
谢谢你,迪米特!现在我明白了。xsl:sort只是转换的前一个版本的遗留部分。谢谢你的提示,我会删除它。
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>
<xsl:template match="myRoot">
<xsl:apply-templates select="myNode">
<xsl:sort select="@myAttribute" />
<xsl:with-param name="myParam" select="max(myNode/@myAttribute)" />
</xsl:apply-templates>
</xsl:template>
<xsl:template match="myNode[node() and @myAttribute = $myParam]">
<xsl:param name="myParam" />
<xsl:for-each select="myChildAttribute">
INSERT INTO a(b) VALUES ('<xsl:value-of select="@myChildAttribute" />');
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
XPST0008: Variable myParam has not been declared (or its declaration is not in scope)
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>
<xsl:template match="myRoot">
<xsl:apply-templates select="myNode[@myAttribute = max(../myNode/@myAttribute)]">
<xsl:sort select="@myAttribute" />
</xsl:apply-templates>
</xsl:template>
<xsl:template match="myNode[node()]">
<xsl:for-each select="myChildAttribute">
INSERT INTO a(b) VALUES ('<xsl:value-of select="@myChildAttribute" />');
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
<myRoot>
<myNode myAttribute="3">
<myChildAttribute myChildAttribute="a" />
</myNode>
<myNode myAttribute="2">
<myChildAttribute myChildAttribute="b" />
</myNode>
<myNode myAttribute="1" />
</myRoot>
INSERT INTO a(b) VALUES ('a');