title: Count nodes based on the sort function of for-each loop in xslt 1.0
body: <p>The input xml has following hierarchy.</p>
  
  <pre><code>&lt;a&gt;  
   &lt;b&gt;
    &lt;b1&gt;3&lt;/b1&gt; 
    &lt;c&gt; 
      &lt;d&gt;
      &lt;d1&gt;13&lt;/d1&gt;
      &lt;d2&gt;text1&lt;/d2&gt; 
      &lt;/d&gt;
      &lt;d&gt;
      &lt;d1&gt;14&lt;/d1&gt;
      &lt;d2&gt;text2&lt;/d2&gt;
      &lt;/d&gt;   
      &lt;d&gt;
      &lt;d1&gt;12&lt;/d1&gt;
      &lt;d2&gt;text3&lt;/d2&gt; 
      &lt;/d&gt;
    &lt;/c&gt;  
   &lt;/b&gt;  
   &lt;b&gt;
    &lt;b1&gt;2&lt;/b1&gt; 
    &lt;c&gt;  
      &lt;d&gt; 
      &lt;d1&gt;11&lt;/d1&gt;
      &lt;d2&gt;text5&lt;/d2&gt;
      &lt;/d&gt;
      &lt;d&gt;
      &lt;d1&gt;10&lt;/d1&gt;
      &lt;d2&gt;text4&lt;/d2&gt;
      &lt;/d&gt;
    &lt;/c&gt;  
   &lt;/b&gt; 
    ---- and so on.
  &lt;/a&gt;
  </code></pre>
  
  <p>I have a xsl template where part of it looks like</p>
  
  <pre><code>    &lt;xsl:for-each select="a/b"&gt;
      &lt;xsl:sort select="b1" data-type="number"/&gt;
      ----- other mapping---
       &lt;xsl:for-each select="c/d"&gt;
       &lt;xsl:sort select="d1" data-type="number"/&gt;
         &lt;xsl:variable name="cnt"&gt;
         &lt;xsl:value-of select="count(preceding::../../c/d)"/&gt;
        &lt;/xsl:variable&gt;
       ------ other mapping------
       &lt;/xsl:for-each&gt;
      &lt;/xsl:for-each&gt;
  </code></pre>
  
  <p>Now even after applying sort function, the count function is following the order of 'd' in the input xml and not based on sorted ascending order of 'd' in the for-each statement.
  <strong>for-eg In loop 2 of element b i.e. b[position()=2] i am getting  cnt = 3 though it should be 2.</strong> Please advice.</p>