2012-02-27 56 views
4

當我有這樣的XSL:XSL Basics:顯示布爾值的值?

<xsl:choose> 
    <xsl:when test="something > 0"> 
    <xsl:variable name="myVar" select="true()"/> 
    </xsl:when> 
    <xsl:otherwise> 
    <xsl:variable name="myVar" select="false()"/> 
    </xsl:otherwise> 
</xsl:choose> 

我怎樣才能然後打印出「myVar的」的價值?或者更重要的是,如何在另一個選擇語句中使用此布爾值?

回答

7
<xsl:choose> 
    <xsl:when test="something > 0"> 
    <xsl:variable name="myVar" select="true()"/> 
    </xsl:when> 
    <xsl:otherwise> 
    <xsl:variable name="myVar" select="false()"/> 
    </xsl:otherwise> 
</xsl:choose> 

這是非常錯誤的,無用的,因爲變量$myVar超出範圍立即

一個有條件賦值給變量正確的方法是:

<xsl:variable name="myVar"> 
    <xsl:choose> 
    <xsl:when test="something > 0">1</xsl:when> 
    <xsl:otherwise>0</xsl:otherwise> 
    </xsl:choose> 
</xsl:variable> 

不過,你真的不需要這一點 - 更簡單的是

<xsl:variable name="myVar" select="something > 0"/> 
How can I then print out the value of "myVar"? 

使用

<xsl:value-of select="$myVar"/> 

或者更重要的是,我該如何使用這個布爾在另一個選擇 聲明?

下面是一個簡單的例子:

<xsl:choose> 
    <xsl:when test="$myVar"> 
    <!-- Do something --> 
    </xsl:when> 
    <xsl:otherwise> 
    <!-- Do something else --> 
    </xsl:otherwise> 
</xsl:choose> 

這裏是一個完整的例子

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 

<xsl:template match="/*/*"> 
    <xsl:variable name="vNonNegative" select=". >= 0"/> 

    <xsl:value-of select="name()"/>: <xsl:text/> 

    <xsl:choose> 
    <xsl:when test="$vNonNegative">Above zero</xsl:when> 
    <xsl:otherwise>Below zero</xsl:otherwise> 
    </xsl:choose> 
</xsl:template> 
</xsl:stylesheet> 

當施加在下面的XML文檔這一轉變:

<temps> 
<Monday>-2</Monday> 
<Tuesday>3</Tuesday> 
</temps> 

的希望,正確的結果產生

Monday: Below zero 
Tuesday: Above zero 
+0

謝謝你,我的一切要求!對於這個沒有問題的問題抱歉,我剛開始並沒有覺得這很直觀! – 2012-02-27 23:08:30

+0

@ ing0:不客氣。 – 2012-02-27 23:10:38

+0

如果你不介意回答這個問題,有沒有辦法在xsl中做一個if語句?我在某處讀了一些信息,並沒有把你的陳述放在那裏,但這對我來說似乎不起作用!再次感謝這裏的答案:) – 2012-02-27 23:38:31