Note that there are some explanatory texts on larger screens.

plurals
  1. POSorting a nodeset before passing to xsl:for-each
    primarykey
    data
    text
    <p>I have a situation where loop through a sorted nodeset and apply a template on each of the nodes:</p> <pre><code>&lt;div id="contractscontainer"&gt; &lt;xsl:for-each select="document"&gt; &lt;xsl:sort select="content[@name='ClientName']/text()" /&gt; &lt;xsl:apply-templates select="." mode="client-contract" /&gt; &lt;/xsl:for-each&gt; &lt;/div&gt; </code></pre> <p>I want to do something special with the "first" 5 nodes in the node set and render them nested element. The problem is that they need to be in the same order as if they were sorted (as they are in the loop).</p> <p>I had planned on doing this by using two <code>xsl:for-each</code> elements, each with the correct nodes selected from the set. I can't do this, however, because they need to be sorted <em>before</em> I can select the "first" 5.</p> <p>Example:</p> <pre><code>&lt;div id="contractscontainer"&gt; &lt;div class="first-five"&gt; &lt;xsl:for-each select="document[position() &lt; 6]"&gt; &lt;xsl:sort select="content[@name='ClientName']/text()" /&gt; &lt;xsl:apply-templates select="." mode="client-contract" /&gt; &lt;/xsl:for-each&gt; &lt;/div&gt; &lt;div class="rest-of-them"&gt; &lt;xsl:for-each select="document[position() &gt; 5]"&gt; &lt;xsl:sort select="content[@name='ClientName']/text()" /&gt; &lt;xsl:apply-templates select="." mode="client-contract" /&gt; &lt;/xsl:for-each&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I don't think this will work because I'm selecting the nodes by position <em>before</em> sorting them, but I can't use <code>xsl:sort</code> outside of the <code>xsl:for-each</code>.</p> <p>Am I approaching this incorrectly?</p> <p><strong>Edit</strong>: My current solution is to sort them and store the sorted set in another variable:</p> <pre><code>&lt;xsl:variable name="sorted-docs"&gt; &lt;xsl:for-each select="document"&gt; &lt;xsl:sort select="content[@name='ClientName']/text()" /&gt; &lt;xsl:copy-of select="." /&gt; &lt;/xsl:for-each&gt; &lt;/xsl:variable&gt; </code></pre> <p>It works, but is there a better way?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload