質問

条件の結果に基づいて異なるパラメーターを使用してテンプレートを適用したい。このようなもの:

<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 開始/終了タグでラップしようとしましたが、それは明らかに違法です。手がかりはありますか?

役に立ちましたか?

解決

別の方法は、xsl:param要素内にxsl:chooseステートメントを配置することです

<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 は1つだけになりますが、複数の 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