2014-10-26 85 views
1

當我運行下面的代碼...如何在XSLT中聲明變量?

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

<xsl:template match="images"> 
<ul id="tiles"> 
    <xsl:for-each select="entry"> 
     <li> 
      <xsl:if test="position() mod 4 = 0"> 
       <xsl:attribute name="class">fourth</xsl:attribute> 
      </xsl:if> 

      <xsl:choose> 
       <xsl:when test="datei/meta/@width &gt; datei/meta/@height">   
        <xsl:variable name="width">600</xsl:variable> 
        <xsl:variable name="height">450</xsl:variable>        
       </xsl:when> 
       <xsl:when test="datei/meta/@width &lt; datei/meta/@height">         
        <xsl:variable name="width">600</xsl:variable> 
        <xsl:variable name="height">800</xsl:variable>      
       </xsl:when> 
       <xsl:otherwise> 
        <xsl:variable name="width">600</xsl:variable> 
        <xsl:variable name="height">600</xsl:variable> 
       </xsl:otherwise> 
      </xsl:choose> 

      <a href="{$root}/image/2/{$width}/{$height}/5{datei/@path}/{datei/filename}" class="fresco" data-fresco-caption="{titel}" data-fresco-group="event"> 
       <img src="{$root}/image/2/320/320/5{datei/@path}/{datei/filename}"/> 
      </a> 
     </li> 
    </xsl:for-each> 
</ul> 
</xsl:template> 

</xsl:stylesheet> 

我得到一個錯誤:

XSLTProcessor::transformToXml(): 
Variable 'width' has not been declared. 
xmlXPathCompiledEval: evaluation failed 
Variable 'height' has not been declared. 
xmlXPathCompiledEval: evaluation failed 

這怎麼可能?

我是否以錯誤的方式聲明變量widthheight

感謝您的任何幫助。

回答

2

我有時喜歡使用模板規則如下:

<xsl:variable name="width"> 
    <xsl:apply-templates select="datei/meta/@width" mode="width"/> 
</xsl:variable> 

<xsl:template match="@width[. &gt; ../@height]" mode="width">600</xsl:template> 
<xsl:template match="@width[. &lt; ../@height]" mode="width">600</xsl:template> 
<xsl:template match="@width" mode="width">600</xsl:template> 

模板規則的XSLT中最常用的部分。

+0

我剛剛意識到這是解決我的問題的更好方法。 – Tintin81 2014-12-07 12:07:57

1

這是一個XSLT變量範圍的問題。您已將變量聲明在您想要使用它們的範圍之外。重新播放變量聲明,以便xsl:choose語句落入聲明中,而不是其他方式。

+0

好的,謝謝。但是,這究竟是什麼樣子?我對XSL仍然很陌生,所以我不確定你的意思。 – Tintin81 2014-10-26 18:28:59

2

你可以聲明變量高度例如是這樣的:

<xsl:variable name="height"> 
<xsl:choose> 
    <xsl:when test="datei/meta/@width &gt; datei/meta/@height">   
     <xsl:value-of select="'450'"/>       
    </xsl:when> 
    <xsl:when test="datei/meta/@width &lt; datei/meta/@height"> 
     <xsl:value-of select="'800'"/>       
    </xsl:when> 
    <xsl:otherwise> 
     <xsl:value-of select="'600'"/> 
    </xsl:otherwise> 
</xsl:choose> 
</xsl:variable> 

由於寬度始終是600,沒有必要宣佈它爲變量,但也許只適用於你所提供的例子,在其他情況下寬度可能會有所不同

在內部聲明的變量一個<xsl:choose>聲明不在此範圍之外。由於目前已經有類似的問題提供了很好的解釋,就像一個參考這樣的回答:Variable scope in XSLT

+0

工作正常!非常感謝你。 – Tintin81 2014-10-26 19:59:03