2017-04-21 56 views
0

我有一種記分牌,想要計算出勝出的隊伍。但不幸的是,我無法計算id值的出現次數。下面是示例XML文檔:選擇元素內的XSL計數()

<?xml version="1.0" encoding="UTF-8"?> 
<?xml-stylesheet type="text/xsl" href="winner.xsl" ?> 
<wm> 
    <game> 
     <team id='de' /> 
     <team id='fr' /> 
     <result>4:2</result> 
    </game> 
    <game> 
     <team id='us' /> 
     <team id='de' /> 
     <result>4:2</result> 
    </game> 
    <game> 
     <team id='de' /> 
     <team id='fr' /> 
     <result>3:2</result> 
    </game> 
    <game> 
     <team id='de' /> 
     <team id='fr' /> 
     <result>1:3</result> 
    </game> 
</wm> 

,並在xsl:

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

<xsl:template match="wm/game/result"> 
<xsl:variable name="tore1" select="substring-before(.,':')"/> 
<xsl:variable name="tore2" select="substring-after(.,':')"/> 

<xsl:choose> 
    <xsl:when test="$tore1 &gt; $tore2"> 
     <xsl:value-of select="../team[1]/@id"/><br /> 
    </xsl:when> 
    <xsl:otherwise> 
     <xsl:value-of select="../team[2]/@id"/><br /> 
    </xsl:otherwise> 
</xsl:choose> 

我設置一個遊戲的贏家,通過比較結果的目標,選擇團隊[1 ]或團隊[2]。輸出是:

de 
us 
de 
fr 

但現在我堅持計數的國家出現。如果我設置計數()的XPath表達式像

<xsl:value-of select="count(../team[1]/@id)" /> 

它導致:

1 
1 
1 
1 

而且

<xsl:value-of select="count(../team[@id = 'de'])"/> 

的選擇語句外做了相同的輸出。我想有以下輸出

2 de 
1 us 
1 fr 

感謝您的幫助。

+1

這是一個分組問題,它是一個計數問題之前。你有參賽隊伍的名單嗎?還是你需要按照輸入中列出的任何球隊對比賽進行分組? –

回答

1

算一個已知團隊的勝利次數很容易。請看下面的例子:

<xsl:template match="/wm"> 
    <xsl:variable name="id" select="'de'"/> 
    <xsl:variable name="home-wins" select="count(game[team[1]/@id=$id][substring-before(result, ':') > substring-after(result, ':')])"/> 
    <xsl:variable name="away-wins" select="count(game[team[2]/@id=$id][substring-after(result, ':') > substring-before(result, ':')])"/> 
    <xsl:value-of select="$home-wins + $away-wins"/> 
    <xsl:text> </xsl:text> 
    <xsl:value-of select="$id"/> 
</xsl:template> 

結果

2 de 
+0

將Meunchian組合與識別輸入文檔中表示的所有團隊並輸出每個團隊的勝利數量並不難。 –

0

感謝。 @ michael.hor257k的答案正常。我也嘗試應用Meunchian分組。我想我明白了。謝謝你的幫助。

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


<xsl:key name="teamsByID" match="game/team" use="@id"/> 

<xsl:template match="wm"> 

    <xsl:for-each select="game/team[count(. | key('teamsByID', @id)[1]) = 1]"> 
    <xsl:variable name="id" select="@id"/> 
    <xsl:variable name="tore1" select="count(../../game[team[1]/@id=$id][substring-before(result,':') > substring-after(result, ':')])" /> 
    <xsl:variable name="tore2" select="count(../../game[team[2]/@id=$id][substring-after(result,':') > substring-before(result, ':')])" /> 
    <xsl:value-of select="$tore1 + $tore2"/> - <xsl:value-of select="@id"/><br /> 
    </xsl:for-each> 

</xsl:template>