Count matches : count « XSLT stylesheet « XML Tutorial






File: Data.xml 

<?xml version="1.0"?>
<results group="A">
  <match>
    <date>10-Jun-98</date>
    <team score="2">team 1</team>
    <team score="1">team 2</team>
  </match>
  <match>
    <date>10-Jun-98</date>
    <team score="2">team 3</team>
    <team score="2">team 4</team>
  </match>
  <match>
    <date>16-Jun-98</date>
    <team score="1">team 2</team>
    <team score="1">team 4</team>
  </match>
</results>

File: Transform.xslt
<?xml version="1.0"?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="2.0">

  <xsl:variable name="teams" select="distinct-values(//team)" />
  <xsl:variable name="matches" select="//match" />

  <xsl:template match="results">
    <league>
      <xsl:for-each select="$teams">
        <xsl:variable name="this" select="." />
        <xsl:variable name="played"
          select="count($matches[team=$this])" />
        <xsl:variable name="won"
          select="count($matches[team[.=$this]/@score &gt; team[.!=$this]/@score])" />
        <xsl:variable name="lost"
          select="count($matches[team[.=$this]/@score &lt; team[.!=$this]/@score])" />
        <xsl:variable name="drawn"
          select="count($matches[team[.=$this]/@score = team[.!=$this]/@score])" />
        <xsl:variable name="for"
          select="sum($matches/team[.=current()]/@score)" />
        <xsl:variable name="against"
          select="sum($matches[team=current()]/team/@score) - $for" />

        <team name="{.}" played="{$played}" won="{$won}"
          drawn="{$drawn}" lost="{$lost}" for="{$for}" against="{$against}" />

      </xsl:for-each>
    </league>
  </xsl:template>

</xsl:transform>

Output:

<?xml version="1.0" encoding="UTF-8"?><league>
<team name="team 1" played="1" won="1" drawn="0" 
lost="0" for="2" against="1"/><team name="team 2" 
played="2" won="0" drawn="1" lost="1" for="2" against="3"/>
<team name="team 3" played="1" won="0" drawn="1" lost="0" 
for="2" against="2"/><team name="team 4" played="2" won="0" 
drawn="2" lost="0" for="3" against="3"/></league>








5.10.count
5.10.1.count()- Takes a node-set argument and returns a value equal to the number of nodes in the node-set
5.10.2.Use count function in math calculation
5.10.3.Count matches
5.10.4.Count node
5.10.5.count elements which occured in XML source
5.10.6.The count function returns the number of nodes in the argument node-set.