Re: [xsl] Count all instances of a named element in a tree

Subject: Re: [xsl] Count all instances of a named element in a tree
From: "G. Ken Holman" <gkholman@xxxxxxxxxxxxxxxxxxxx>
Date: Fri, 29 May 2009 11:53:45 -0400
At 2009-05-29 16:48 +0100, W Charlton wrote:
Does anyone know an elegant solution to counting all elements in an XML
fragment where the elements to be counted are nested in a tree? An example
of the XML is below:

Perhaps I'm missing something, but you can just use count() and address the nodes you want. Are you asking, perhaps, about some kind of qualification of nodes?


The count in this case would be 8.

I hope the example below helps.


. . . . . . . Ken

T:\ftemp>type charlton.xml
   <xmltree>
      <countmein>Node1</countmein>
      <nodes>
         <node>
            <countmein>Node2</countmein>
            <level>1</level>
            <nodes>
               <node>
                  <countmein>Node3</countmein>
                  <level>2</level>
                  <nodes>
                     <node>
                        <countmein>Node4</countmein>
                        <level>3</level>
                        <nodes/>
                    </node>
                 </nodes>
              </node>
              <node>
                 <countmein>Node5</countmein>
                 <level>2</level>
                 <nodes/>
              </node>
              <node>
                 <countmein>Node6</countmein>
                 <level>2</level>
                 <nodes/>
              </node>
           </nodes>
        </node>
        <node>
           <countmein>Node7</countmein>
           <level>1</level>
           <nodes>
              <node>
                 <countmein>Node8</countmein>
                 <level>2</level>
                 <nodes/>
              </node>
           </nodes>
        </node>
     </nodes>
   </xmltree>

T:\ftemp>call xslt charlton.xml charlton.xsl
8
T:\ftemp>type charlton.xsl
<?xml version="1.0" encoding="US-ASCII"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
                version="2.0">

<xsl:output method="text"/>

<xsl:template match="/">
  <xsl:value-of select="count(//countmein)"/>
</xsl:template>

</xsl:stylesheet>

T:\ftemp>

--
XSLT/XSL-FO/XQuery hands-on training - Los Angeles, USA 2009-06-08
Crane Softwrights Ltd.          http://www.CraneSoftwrights.com/s/
Training tools: Comprehensive interactive XSLT/XPath 1.0/2.0 video
Video lesson:    http://www.youtube.com/watch?v=PrNjJCh7Ppg&fmt=18
Video overview:  http://www.youtube.com/watch?v=VTiodiij6gE&fmt=18
G. Ken Holman                 mailto:gkholman@xxxxxxxxxxxxxxxxxxxx
Male Cancer Awareness Nov'07  http://www.CraneSoftwrights.com/s/bc
Legal business disclaimers:  http://www.CraneSoftwrights.com/legal

Current Thread