2013-11-01 42 views
1

目前,我的文件中有很多「xsl:choose」條件 - 一個字母爲「xsl:choose」,並且效果很好。 我試圖通過用'for-each'循環替換許多「xsl:choose」來簡化這種情況 - 但是沒有運氣。'for-each'中的Count()總是返回零

在我看來,'for-each'裏面的count()總是返回0. 我很好奇,因爲沒有'for-each'的同樣的count()工作正常。

請幫忙。

<?xml version="1.0"?> 
<stocks> 
<names date="10/30/2013" time="20:37:12"> 
    <name>WGOS1</name> 
    <name>WGOS2</name> 
    <name>WGOS3</name> 
    <name>WGOS4</name> 
    <name>WGOS5</name> 
</names> 
<loc> 
    <slot>P</slot> 
    <slot>P</slot> 
    <slot>P</slot> 
    <slot>P</slot> 
    <slot>H</slot> 
    <slot>S</slot> 
</loc> 
<loc> 
    <slot>P</slot> 
    <slot>P</slot> 
    <slot>P</slot> 
    <slot>S</slot> 

當我使用'計數'功能來計數值,例如。在「祿」節點「B」,它的工作原理確定

<xsl:variable name="color-table"> 
    <var code="A">pink</var > 
    <var code="B">silver</var> 
    <var code="P">red</var> 
    <var code="D">pink</var> 
    <var code="H">yellow</var> 
    <var code="S">lightblue</var> 
    <var code="T">green</var> 
    <var code="W">pink</var> 
</xsl:variable> 

<xsl:template match="/">  

<xsl:choose> 
    <xsl:when test="count(/stocks/loc[$pos]/slot [. eq 'B']) &gt; 0"> 
     <td class="slot-B"> 
      <xsl:value-of select="count(/stocks/loc[$pos]/slot [. eq 'B'])"/> 
      <xsl:text>B</xsl:text> 
     </td> 
    </xsl:when> 
    </xsl:choose> 

但是,當我嘗試做for-each循環相同的內部 - 測試條件失敗,由於計數()的結果始終爲0

<xsl:for-each select="$color-table/var"> 
    <xsl:variable name="p" select="@code"/> 
    <xsl:choose> 
     <xsl:when test="count(/stocks/loc[$pos]/slot [. eq $p]) &gt; 0"> 
      <td class="slot-$p"> 
       <xsl:value-of select="count(/stocks/loc[$pos]/slot [. eq $p])"/> 
       <xsl:value-of select="$p"/> 
      </td> 
     </xsl:when> 
    </xsl:choose> 
    </xsl:for-each> 

回答

1

$color-table變量是指一個臨時的樹,所以當你在裏面一個

<xsl:for-each select="$color-table/var"> 

/是暫時的樹,而不是原始文檔的根本中的根本,因而/stocks/loc[$pos]/slot將找不到任何節點。

在進入for-each之前,您需要將外部/存儲在另一個變量中。

<xsl:variable name="slash" select="/" /> 
<xsl:for-each select="$color-table/var"> 
<xsl:variable name="p" select="@code"/> 
<xsl:choose> 
    <xsl:when test="count($slash/stocks/loc[$pos]/slot [. eq $p]) &gt; 0"> 
     <td class="slot-{$p}"> 
      <xsl:value-of select="count($slash/stocks/loc[$pos]/slot [. eq $p])"/> 
      <xsl:value-of select="$p"/> 
     </td> 
    </xsl:when> 
</xsl:choose> 
</xsl:for-each> 

但是,而不是遍歷顏色表,它可能是更有效的,只是for-each-group在槽本身

<xsl:for-each-group select="/stocks/loc[$pos]/slot" group-by="."> 
    <td class="slot-{current-grouping-key()}"> 
    <xsl:value-of select="count(current-group())" /> 
    <xsl:value-of select="current-grouping-key()" /> 
    </td> 
</xsl:for-each-group> 
+0

我想' '應該是'',儘管這不是問題的一部分。 –

+0

@MartinHonnen確實會更有意義。 –