title: Selecting the two elements with the lowest attribute values and merging them into one element in the output
body: <p>Using xslt/xpath, I need to be able to select <strong>the two elements which have the lowest attribute value and merge them</strong>, in a way. Lets say for example I have:</p>
  
  <pre><code>&lt;root&gt;
      &lt;integer val="14"/&gt;
      &lt;integer val="7"/&gt;
      &lt;integer val="2"/&gt;
      &lt;integer val="1"/&gt;
      &lt;integer val="4"/&gt;  
      &lt;integer val="8"/&gt;
  &lt;/root&gt;
  </code></pre>
  
  <p>I want to select the two lowest values (1 and 2) and represent them as one element in the output. The attribute value should be the sum of these two lowest values, so I want:</p>
  
  <pre><code>&lt;root&gt;
      &lt;integer val="3"/&gt;
  &lt;/root&gt;
  </code></pre>
  
  <p>I am also constrained to using <strong>only xslt 1.0</strong>, as the xml is to be processed with the java 1.5 api, which does not seem to support xslt 2.0. What should i do to make my stylesheet solve this seemingly simple task?</p>
  
  <hr>
  
  <p>My first attempt was to use sorting:</p>
  
  <pre><code>&lt;xsl:template match="root"&gt;
  &lt;xsl:copy&gt;
      &lt;xsl:apply-templates select="integer"&gt;
          &lt;xsl:sort data-type="number" select="@val"/&gt;        
      &lt;/xsl:apply-templates&gt;
  &lt;/xsl:copy&gt;
  &lt;/xsl:template&gt;
  
  
  
  &lt;xsl:template match="integer[1]"&gt; 
  &lt;xsl:copy&gt;
      &lt;xsl:attribute name="val"&gt;
          &lt;xsl:value-of select="@val + ../integer[2]/@val"/&gt;
      &lt;/xsl:attribute&gt;
  &lt;/xsl:copy&gt;
  &lt;/xsl:template&gt;
  </code></pre>
  
  <p>This however results in nothing. Only an empty root node. Apparently, the &lt;xsl:sort&gt; disables the ability to do &lt;xsl:template match="integer[1]"&gt; (the [1] part is the part that does not work together with the sort). And, even if it did work, the [1] seems to refer to the document order, not the sorted order. Changing the second template to:</p>
  
  <pre><code>&lt;xsl:template match="integer"&gt; 
  &lt;xsl:copy&gt;
      &lt;xsl:attribute name="val"&gt;
          &lt;xsl:value-of select="../integer[2]/@val"/&gt;
      &lt;/xsl:attribute&gt;
  &lt;/xsl:copy&gt;
  &lt;/xsl:template&gt;
  </code></pre>
  
  <p>Results in output where all output val attributes are 7 (instead of 2, which I wanted it to be)</p>
  
  <p>Another approach was to use the min() xpath function. This however, failed fast since min() is not available in 1.0. And, even if min were available, it would not be trivial to find the <strong>two</strong> smallest elements and merge those.</p>