如何将参数从一个XSLT模板传递到另一个



我在向模板传递参数时遇到麻烦。

<!-- // Product / Instances -->
<xsl:template match="/data/products/instances">
    <ul>
        <xsl:apply-templates select="item">
            <xsl:with-param name="idp" select="@id"/>
        </xsl:apply-templates>
    </ul>
</xsl:template>
<!-- // Product / Instances / Instance -->
<xsl:template match="/data/products/instances/item">
    <xsl:param name="idp"/>
    <p>$idp: <xsl:value-of select="$idp"/></p> <!-- $idp is empty -->
    <xsl:for-each select="/data/instances/entry">
        <xsl:if test="@id = $idp">
            <p><xsl:value-of select="code"/></p>
        </xsl:if>
    </xsl:for-each>
</xsl:template>

/data/products/instances/item有一个名为id的属性,该属性的值为整数。

虽然第二个模板和它的for-each循环正在被处理(我已经通过从它们内部输出虚拟输出来测试它们),但$idp参数的值没有传递给第二个模板。

谢谢。

问题在于,当您执行应用模板时,当前上下文位于instances元素上,因此属性@id指的是instances元素的属性id,而不是您将要选择的元素上的属性(此时尚未被选中)。

在给出的示例中,实际上不需要传递参数。只需在匹配模板中使用一个变量即可。代替xsl:param,执行以下操作:

<xsl:variable name="idp" select="@id"/>

这将为您获取id属性的值,因为此时您位于item元素上。

您需要显示足够的细节,以便我们重现问题,否则很难判断出哪里出了问题。

我认为你不需要任何参数,你应该使用一个键

<xsl:key name="k1" match="data/instances/entry" use="@id"/>
<!-- // Product / Instances -->
<xsl:template match="/data/products/instances">
    <ul>
        <xsl:apply-templates select="item"/>
    </ul>
</xsl:template>
<!-- // Product / Instances / Instance -->
<xsl:template match="/data/products/instances/item">
    <xsl:for-each select="key('k1', @id)">
            <p><xsl:value-of select="code"/></p>
    </xsl:for-each>
</xsl:template>

相关内容

最新更新