2010-01-12 125 views
0

我使用,我已經創建<xsl:template>標籤,它不使用<xsl:for-each>聲明瞭一些驗證和設置的<xsl:variable><xsl:param>價值真或假的XSLT條件。XSLT:模板標籤變量和使用打破for-each循環

  1. 如果條件爲真,是否有任何方法可以打破for-each中的語句?
  2. 我們可以使用來自主調用例程的Template變量或param的值嗎?

例子:

<!-- Main Xslt --> 
<xsl:template> 
    <xsl:call-template name ="TestTemplate"> 
    <!-- 
     Here I want to use the variable or param that 
     is defined in TestTemplate, is it possible? 
    --> 
    </xsl:call-template> 
</xsl:template> 

<xsl:template name ="TestTemplate"> 
    <xsl:param name="eee"/> 
    <xsl:for-each select ="//RootNode/LeafNode"> 
    <xsl:choose> 
     <xsl:when test ="@Type='ABC'"> 
     <xsl:value-of select ="true"/> 
     </xsl:when> 
     <xsl:otherwise>false</xsl:otherwise> 
    </xsl:choose> 
    </xsl:for-each> 
</xsl:template> 

回答

0

廣告1.我認爲這是不可能的,但我不知道

廣告2.是的,你可以使用參數,但它關注,因爲它是恆定的。 XSL中的所有變量和參數都是常量。看看W3School - variable

舉:

一旦您設置一個變量的值,你不能改變或修改該值!

同樣的事情是參數。

可以調用帶(恆定)參數模板:

<call-template name="myTemplate"> 
    <xsl:with-param name="name" select="expression"> 
</call-template> 

W3School - with parameter真的是很好的參考頁。

3

您的問題:

有什麼辦法打破本聲明的for-each如果條件是真的嗎?

不,通常這也是不必要的。 XSLT不是命令式編程語言,命令式的方法在這裏並不適用。

你似乎想做什麼是表達「找到的第一個<LeafNode>其中@Type='ABC',並返回true或false取決於是否有一個

傳統語言要做到這一點的方法是喜歡你的做法:對每個節點,檢查條件,如果條件滿足,則返回

在XSLT,您只需選擇節點使用XPath:

//RootNode/LeafNode[@Type='ABC'] 

任該結果包含一個節點,或者我t不。沒有必要爲每一個。

我們可以使用來自主調用例程的模板變量或參數的值嗎?

不是。變量和參數的範圍是嚴格的。一旦處理離開其父元素,它們就會超出範圍。他們也是不變的,一旦宣佈他們不能改變。

做你想要的這裏的方式是使模板輸出所需的值,並捕獲它的一個變量:

<xsl:template> 
    <xsl:variable name="returnValue"> 
    <xsl:call-template name="TestTemplate" /> 
    </xsl:variable> 
</xsl:template> 

<xsl:template name="TestTemplate"> 
    <!-- the following expression emits true or false --> 
    <xsl:value-of select=" 
    count(//RootNode/LeafNode[@Type='ABC']) gt; 0 
    " /> 
</xsl:template> 

最後兩個提示:

  • 避免'//'操作不惜一切代價。大部分的它的使用是沒有必要的
  • 第一,最上面的元素在文檔中的時間不是「根節點」,它是「文檔元素」

這是一個重要的區別。 「根節點」前前的文檔元素,所以上面的XPath應該更像這樣(語義上):

/DocumentElement/LeafNode 
^------ *this* slash represents the "root node"