2015-11-20 63 views
0

爲什麼我會得到真正的從該模板返回值:模板返回true()時,被告知要返回false

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
 
\t <xsl:template name="return-false"> 
 
\t \t <xsl:value-of select="false()"/> 
 
\t </xsl:template> 
 
\t <xsl:template match="/"> 
 
\t \t <root> 
 
\t \t \t <xsl:variable name="call-template"> 
 
\t \t \t \t <xsl:call-template name="return-false"/> 
 
\t \t \t </xsl:variable> 
 
\t \t \t <xsl:if test="$call-template = true()"> 
 
\t \t \t \t <FALSE/> 
 
\t \t \t </xsl:if> 
 
\t \t </root> 
 
\t </xsl:template> 
 
</xsl:stylesheet>
猜猜我得到的輸出文檔 FALSE元素 。我想知道我應該哭還是應該笑我對這個簡單例子的掙扎。我的挫折感觸到了天空。

+0

如何提供XML輸入和輸出。 –

+0

我相信沒有這些,就足夠簡單了。 –

回答

4

xsl:value-of指令創建一個文本節點。

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

返回false()功能,這是字符串 「false」 的字串值。所以你的$call-template變量的內容是一個包含字符串「false」的文本節點。

http://www.w3.org/TR/xslt/#value-of

接下來,測試test="$call-template = true()"回報true(),因爲:

  • 您比較文本節點爲布爾值;
  • 與布爾值相比較的節點首先轉換爲布爾值;
  • 存在的節點在轉換爲布爾值時被評估爲true()

http://www.w3.org/TR/xpath/#booleans

1

對值'true''false'進行測試,而不是功能,它的工作原理。你爲什麼這樣做呢?你想達到什麼目的?使用call-template來返回一個布爾值更像是一個過程性的事情,並且可能不適合XSLT的更多功能/聲明模型。

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:template name="return-false"> 
     <xsl:value-of select="false()"/> 
    </xsl:template> 
    <xsl:template match="/"> 
     <root> 
      <xsl:variable name="call-template"> 
       <xsl:call-template name="return-false"/> 
      </xsl:variable> 
      <xsl:if test="$call-template = 'true'"> 
       <FALSE/> 
      </xsl:if> 
     </root> 
    </xsl:template> 
</xsl:stylesheet> 
+0

你是對的,但是不按我的方式工作的原因是什麼? –

+0

查看@ michael.hor257k的回答 - 他明白了第一個 –

+0

模板返回布爾值時,沒有任何內在的過程性或非聲明性。只是它不能在XSLT 1.0中完成; 1.0中的模板總是返回節點(或者,使用1的語言。0規範,將結點寫入結果樹,在本例中,結果樹是由xsl:variable創建的結果樹片段)。 –

1

注意,在XSLT 2.0和3.0中的一個模板或函數可以返回一個布爾值,但不使用value-of,代替使用sequence例如

<xsl:template name="return-false"> 
    <xsl:sequence select="false()"/> 
</xsl:template> 

當然,通常你不會返回一個布爾常量值,而是簡單地評估一個比較例如

<xsl:template name="check"> 
    <xsl:param name="input"/> 
    <xsl:sequence select="matches($input, 'foo')"/> 
</xsl:template> 

當然,使用這種代碼在一個緊湊的形式,你會寫一個函數

<xsl:function name="mf:check"> 
    <xsl:param name="input"/> 
    <xsl:sequence select="matches($input, 'foo')"/> 
</xsl:function> 

與例如叫它<xsl:variable name="check1" select="mf:check('foobar')"/>分別爲<xsl:if test="mf:check('foobar')">..</xsl:if>

相關問題