count elements which occured in XML source : count « XSLT stylesheet « XML Tutorial






File: Data.xml
<?xml version="1.0" encoding="utf-8"?>
<data>
    <AAA>
      <BBB id="b1">
        <CCC name="q" size="12"/>
        <EEE id="e1">
          <SSS/>
        </EEE>
        <CCC weight="45"/>
        <CCC/>
      </BBB>
    </AAA>
    <AAA>
      <EEE id="e2"/>
      <CCC>
        <DDD/>
        <DDD/>
      </CCC>
    </AAA>
</data>
File: Transform.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="/">
      <TABLE border="1" width="90%">
        <TR>
          <td>Element</TH>
          <td>Occurs</TH>
        </TR>
        <xsl:for-each select="/descendant::*">
          <xsl:variable name="pos" select="position()"/>
          <xsl:if test="not(/descendant::*[position() &lt; $pos and name()=name(current())])">
            <TR>
              <TD>
                <xsl:value-of select="name()"/>
              </TD>
              <TD>
                <xsl:value-of select="count(/descendant::*[name()=name(current())])"/>
              </TD>
            </TR>
          </xsl:if>
        </xsl:for-each>
        <TR>
          <td>Total count</TH>
          <td>
            <xsl:value-of select="count(//*)"/>
          </TH>
        </TR>
      </TABLE>
    </xsl:template>
</xsl:stylesheet>

Output:

<?xml version="1.0" encoding="UTF-8"?><TABLE border="1" width="90%"><TR><td>Element</TH><td>Occurs</TH></TR><TR><TD>data</TD><TD>1</TD></TR><TR><TD>AAA</TD><TD>2</TD></TR><TR><TD>BBB</TD><TD>1</TD></TR><TR><TD>CCC</TD><TD>4</TD></TR><TR><TD>EEE</TD><TD>2</TD></TR><TR><TD>SSS</TD><TD>1</TD></TR><TR><TD>DDD</TD><TD>2</TD></TR><TR><td>Total count</TH><td>13</TH></TR></TABLE>








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.