title: How to access values from previous and next element in sorted xsl:for-each loop
body: <p>I am using a xsl:for-each loop to sort elements according to their @id-attribute. I need to get the @id-attributes of the previous and next element in the loop.</p>
  
  <p>I've been trying around with the preceding-sibling:: and following-sibling axis, to no avail. I also tried</p>
  
  <pre><code>&lt;xsl:variable name="current_pos" select="position()"/&gt;
  &lt;xsl:value-of select="(//chapter)[($current_pos - 1)]/id&gt;
  </code></pre>
  
  <p>but this returns the attribute values of the unsorted data.</p>
  
  <p>Sample XML data:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;root&gt;
      &lt;chapter id="t19"/&gt;
      &lt;chapter id="a23"/&gt;
      &lt;chapter id="c-0"/&gt;
      &lt;chapter id="d42"/&gt;
      &lt;chapter id="c-1"/&gt;
  &lt;/root&gt;
  </code></pre>
  
  <p>Sample XSLT style sheet:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="3.0"&gt;
  
      &lt;xsl:template match="/root"&gt;
          &lt;xsl:for-each select="chapter"&gt;
              &lt;xsl:sort select="@id"/&gt;
              &lt;xsl:variable name="current_id" select="@id"/&gt;
              Chapter id: &lt;xsl:value-of select="$current_id"/&gt;
              Sorted position: &lt;xsl:value-of select="position()"/&gt;
              Sorted predecessor chapter id: ? &lt;!-- no idea but most important --&gt;
              Sorted follower chapter id: ? &lt;!-- no idea but most important --&gt;
              &lt;xsl:text&gt;&amp;#xa;&lt;/xsl:text&gt;
          &lt;/xsl:for-each&gt;
      &lt;/xsl:template&gt;
  
  &lt;/xsl:stylesheet&gt;
  </code></pre>
  
  <p>The result I would need:</p>
  
  <pre><code>Chapter id: a23
  Sorted position: 1
  Sorted predecessor chapter id: none 
  Sorted follower chapter id: c-0
  
  Chapter id: c-0
  Sorted position: 2
  Sorted predecessor chapter id: a23 
  Sorted follower chapter id: c-1     
  
  Chapter id: c-1
  Sorted position: 3
  Sorted predecessor chapter id: c-0 
  Sorted follower chapter id: d42
  
  Chapter id: d42
  Sorted position: 4
  Sorted predecessor chapter id: c-1 
  Sorted follower chapter id: t19
  
  Chapter id: t19
  Sorted position: 5
  Sorted predecessor chapter id: d42 
  Sorted follower chapter id: none
  </code></pre>