2

我想根据条件的结果应用具有不同参数的模板。像这样的东西:

<xsl:choose>
    <xsl:when test="@attribute1">
        <xsl:apply-templates select='.' mode='custom_template'>
            <xsl:with-param name="attribute_name" tunnel="yes">Attribute no. 1</xsl:with-param>
            <xsl:with-param name="attribute_value" tunnel="yes"><xsl:value-of select="@attribute1"/></xsl:with-param>
        </xsl:apply-templates>
    </xsl:when>
    <xsl:when test="@attribute2">
        <xsl:apply-templates select='.' mode='custom_template'>
            <xsl:with-param name="attribute_name" tunnel="yes">Attribute no. 2</xsl:with-param>
            <xsl:with-param name="attribute_value" tunnel="yes"><xsl:value-of select="@attribute1"/></xsl:with-param>
        </xsl:apply-templates>
    </xsl:when>
    <xsl:otherwise>
        <xsl:apply-templates select='.' mode='custom_template'>
            <xsl:with-param name="attribute_name" tunnel="yes">Error</xsl:with-param>
            <xsl:with-param name="attribute_value" tunnel="yes">No matching attribute   </xsl:with-param>
            </xsl:apply-templates>
    </xsl:otherwise>
</xsl:choose>

首先,我怀疑这可以通过更好的方式解决。(我对 XSLT 完全陌生,所以请提出改进​​建议并原谅臃肿的代码。)

现在的问题是:我怎么能根据这个条件设置参数,并且仍然在一个xsl:apply-templates?我试图xsl:choose用一个xsl:apply-templates开始/结束标签来包装整个,但这显然是不合法的。有什么线索吗?

4

3 回答 3

10

另一种方法是将 xsl:choose 语句放在 xsl:param 元素中

<xsl:apply-templates select="." mode="custom_template">
   <xsl:with-param name="attribute_name" tunnel="yes">
      <xsl:choose>
         <xsl:when test="@attribute1">Attribute no. 1</xsl:when>
         <xsl:when test="@attribute2">Attribute no. 2</xsl:when>
         <xsl:otherwise>Error</xsl:otherwise>
      </xsl:choose>
   </xsl:with-param>
   <xsl:with-param name="attribute_value" tunnel="yes">
      <xsl:choose>
         <xsl:when test="@attribute1"><xsl:value-of select="@attribute1"/></xsl:when>
         <xsl:when test="@attribute2"><xsl:value-of select="@attribute1"/></xsl:when>
         <xsl:otherwise>No matching attribute </xsl:otherwise>
      </xsl:choose>
   </xsl:with-param>
</xsl:apply-templates>
于 2009-10-21T11:28:53.840 回答
3

您的方法没有问题,但您也可以将条件附加到xsl:template match属性中。这将导致只有一个xsl:apply-templates,但几个xsl:template元素

于 2009-10-21T11:24:17.327 回答
3

您可以通过将条件提取到谓词中来摆脱所有这些逻辑和模式。你没有说你正在处理的元素的名称是什么,但假设它被调用,foo那么这样的东西就足够了:

<xsl:template match="foo[@attribute1]">
    <!-- 
         do stuff for the case when attribute1 is present 
         (and does not evaluate to false) 
    -->
</xsl:template>

<xsl:template match="foo[@attribute2]">
    <!-- 
         do stuff for the case when attribute2 is present 
         (and does not evaluate to false)
    -->
</xsl:template>

<xsl:template match="foo">
    <!-- 
         do stuff for the general case  
         (when neither attribute1 nor attribute 2 are present) 
    -->
</xsl:template>
于 2009-10-21T13:13:37.367 回答