2013-07-31 37 views
0

我想知道是否可以根據屬性值在XSLT(2.0)中分派到<xsl:template>。讓我們假設下面的示例XML:基於屬性值的XSLT中的模板分派

<root> 
    <field code="a">Content A</field> 
    <field code="b">Content B</field> 
</root> 

我要爲<xsl:template>match的屬性,將派遣處理給定屬性的每個值定義的模板寫的XPath選擇。 A不適用ï五個方法可以在每個模板比較屬性值:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    version="2.0"> 

    <xsl:template match="/root"> 
     <xsl:apply-templates select="field"/>  
    </xsl:template> 

    <xsl:template match="field[@code = 'a']"> 
     Code A processing... 
    </xsl:template> 

    <xsl:template match="field[@code = 'b']"> 
     Code B processing... 
    </xsl:template> 

</xsl:stylesheet> 

類似的,可以使用<xsl:choose><xsl:when>每一個可能的碼值,其中可用於<xsl:call-template/>,調用專門命名模板。

有沒有更好的解決方案來做基於屬性值的模板調度?

+0

避免''支持模板匹配,如果可以的話(有時您不能,比如在測試變量或參數值時)。 – Tomalak

+0

準確。我的首選方式絕對是通過使用模板匹配。 –

回答

2

您的代碼在XSLT 1.0和2.0中均有效,這也是一種很好的做法。有什麼問題?

+0

我認爲可能有一種方法可以直接匹配屬性值,從而避免一些重複'field [@code ='dispatch value']'。 –

+0

@jindrichm,你可以在例如'場/ @代碼[。 ='b']'。但是,通常只有在您想將該屬性轉換爲不同的屬性或者至少簡單地輸出其值時纔有意義。如果'field'的轉換或輸出根據屬性而不同,那麼處理匹配元素的模板中的差異通常會更容易。 –