2013-03-04 39 views
1

此問題與XSL store node-set in variable非常相似。主要區別在於,如果XPath找不到與過濾器匹配的節點,我想返回第一個未過濾的結果。使用條件將XSL變量設置爲節點集

我在這裏的代碼工作,但我覺得它是一個黑客和不好的XSL風格。在這種情況下,每個章節節點都由字符串ID標識。變量showChapter是識別章節的字符串。如果沒有找到這個id屬性的章節,我想返回第一章。

相關代碼:

<xsl:param name="showChapter" /> 

<!-- if $showChapter does not match any chapter id attribute, 
    set validShowChapter to id of first chapter. 
--> 

<xsl:variable name="validShowChapter"> 
    <xsl:choose> 
     <xsl:when test="/book/chapter[@id=string($showChapter)][position()=1]"> 
      <xsl:value-of select="$showChapter" /> 
     </xsl:when> 
     <xsl:otherwise> 
      <xsl:value-of select="/book/chapter[position()=1]/@id" /> 
     </xsl:otherwise> 
    </xsl:choose> 
</xsl:variable> 

<!-- I want $chapter to be a valid node-set so I can use it in 
    XPath select statements in my templates 
--> 
<xsl:variable 
    name="chapter" 
    select="/book/chapter[@id=string($validShowChapter)][position()=1]" 
> 

這是方法,因爲差的黑客,因爲我認爲這是,如果這樣你就可以點我到一個更好的解決方案?我正在使用由PHP5的XSLTProcessor處理的XSLT 1.0,但歡迎使用XSLT 2.0解決方案。

回答

1

以下應該工作。很多在你的例子position()string()使用的是不需要的,順便說一句:

<xsl:param name="showChapter" /> 

<xsl:variable name="foundChapter" select="/book/chapter[@id = $showChapter]" /> 
<!-- Will select either the first chapter in $foundChapter, or 
    the first chapter available if $foundChapter is empty --> 
<xsl:variable name="chapter" 
       select="($foundChapter | /book/chapter[not($foundChapter)])[1]" /> 
+0

非常感謝您!我知道我正在寫什麼是最可怕的解決方案。 – Vlad 2013-03-04 08:22:50