title: XSLT; finding most frequent element value in a document
body: <p>Apologies if this is a very simple question; I don't use XSLT very much and I can't find much advice on the web, as there is lots of pollution in search results!</p>
  
  <p>I have an XML document in the following form. Its main purpose is to be reformatted in a few ways by XSLT for display in a couple of different formats.</p>
  
  <pre><code>&lt;desk&gt;
  &lt;drawer&gt;
      &lt;contents&gt;pencils&lt;/contents&gt;
      &lt;quantity&gt;2&lt;/quantity&gt;
  &lt;/drawer&gt;
  &lt;drawer&gt;
      &lt;contents&gt;pens&lt;/contents&gt;
      &lt;quantity&gt;15&lt;/quantity&gt;
  &lt;/drawer&gt;
  &lt;drawer&gt;
      &lt;contents&gt;pencils&lt;/contents&gt;
      &lt;quantity&gt;3&lt;/quantity&gt;
  &lt;/drawer&gt;
  &lt;drawer&gt;
      &lt;contents&gt;rulers&lt;/contents&gt;
      &lt;quantity&gt;2&lt;/quantity&gt;
  &lt;/drawer&gt;
  &lt;/desk&gt;
  </code></pre>
  
  <p>I'd like to extract from the xml two pieces of information: i) the average quantity; ii) the most frequently encountered content by number of appearances in the xml (i.e. "pencils" because it appears twice rather than "pens" because it has the largest quantity). The idea is that this can be piped into a very simple shell script. I therefore thought that the easiest way of getting this information would be to write couple of short xsl style-sheets and then use xsltproc to get the data. </p>
  
  <p>The first piece of information seems straight-forward. The heart of the style-sheet would be this line:</p>
  
  <pre><code>&lt;xsl:value-of select="(sum(drawer/quantity)) div (count(drawer))" /&gt;
  </code></pre>
  
  <p>but I'm a bit stuck by the second.</p>
  
  <p>I think I can use something like this for loop through a list of each individual content:</p>
  
  <pre><code>&lt;xsl:for-each select="drawer[not(contents = preceding-sibling::drawer/contents)]" /&gt;
  </code></pre>
  
  <p>but I'm not quite sure how then to count the number of elements which have $current_contents and the value of their content element. Nor can I see an easy way of then sorting by results so I can get the name of the most frequently encountered value of contents.</p>
  
  <p>I have a feeling this is easier in XSLT 2.0 with its various group-by options, but unfortunately, xsltproc doesn't seem to support that. Any help would be gratefully received. </p>
  
  <p>Many thanks,</p>
  
  <p>Jacob</p>