我想要应用一个模板不同的参数基于结果的一个条件。事情是这样的:

<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:choosexsl:apply-templates 开始-/端的标签,但是显然不合法的。任何线索?

有帮助吗?

解决方案

一个备用的方法将是把xsl:选择发言内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>

其他提示

没错你的方法,但你还可以附加条件进入 xsl:template match 属性。这将导致只有一个 xsl:apply-templates, 但几个 xsl:template 元素

你可以摆脱所有的逻辑和模式提取你们的条件进入谓词。你不说什么名称的元素,你正在处理的,但假设这就是所谓 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>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top