2009-07-10 69 views
2

下並不如預期運行:XSLT:條件屬性值處理

<xsl:template match="xs:complexType"> 
    <xsl:param name="prefix" /> 

    <xsl:if test="$prefix='core'"> 
    <xsl:variable name="prefix" select=""/> 
    </xsl:if> 

    <xs:complexType name="{concat($prefix, @name)}"> 
    <xsl:apply-templates select="node()" /> 
    </xs:complexType> 
    <xsl:apply-templates select=".//xs:element" /> 
</xsl:template> 

的想法是,如果前綴變量值是「核心」,我不希望它被添加到名稱屬性值。任何其他價值,我想補充。 IE:

<xs:complexType name="coreBirthType"> 

...是接受的,而下面將是:

<xs:complexType name="BirthType"> 

但我必須允許這種情況發生:

<xs:complexType name="AcRecHighSchoolType"> 

我試着這在一個塊,但撒克遜抱怨沒有找到一個關閉節點:

<xsl:choose> 
    <xsl:when test="starts-with(.,'core')"> 
    <xs:complexType name="{@name)}"> 
    </xsl:when> 
    <xsl:otherwise> 
    <xs:complexType name="{concat($prefix, @name)}"> 
    </xsl:otherwise> 
</xsl:choose> 
    <xsl:apply-templates select="node()" /> 
</xs:complexType> 

處理這個問題的最佳方法是什麼?

回答

5

在XSLT,作爲一個沒有副作用的純語言,變量是不可變的。您無法更改變量值。如果您聲明另一個<xsl:variable>具有相同的名稱,則可以定義一個新變量,該變量會影響舊的變量。

這裏是你如何能做到這一點:

<xsl:param name="prefix" /> 

<xsl:variable name="prefix-no-core"> 
    <xsl:if test="$prefix != 'core'"> 
    <xsl:value-of select="$prefix" /> 
    </xsl:if> 
</xsl:variable> 

<xs:complexType name="{concat($prefix-no-core, @name)}"> 
... 
+0

是的,一旦設定,不能將值reasign到前綴。 – 2009-07-10 22:36:01

1

那麼,你可以在變量裏面使用if;但在這種情況下,我想我會嘗試<xsl:attribute>

<xs:complexType> 
    <xsl:attribute name="name"><xsl:if test="$prefix != 'core'"><xsl:value-of select-"$prefix"/></xsl:if><xsl:value-of select="@name"/></xsl:attribute> 
    <!-- etc --> 
</xs:complexType> 

if方法:

<xsl:variable name="finalPrefix"><xsl:if test="$prefix != 'core'"><xsl:value-of select="$prefix"/></xsl:if></xsl:variable> 
... 
<xs:complexType name="{$finalPrefix}{@name}"> 
    <!-- etc --> 
</xs:complexType>