Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Here is a more efficient solution, using the classical Muenchian method for grouping -- with keys</strong>.</p> <p><strong>This transformation</strong>:</p> <pre><code>&lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:output omit-xml-declaration="yes" indent="yes"/&gt; &lt;xsl:variable name="vLower" select= "'abcdefghijklmnopqrstuvwxyz'"/&gt; &lt;xsl:variable name="vUpper" select= "'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/&gt; &lt;xsl:key name="kTitleBy1stLetter" match="database" use="substring(title_display,1,1)"/&gt; &lt;xsl:template match="/*"&gt; &lt;xsl:for-each select= "database [generate-id() = generate-id(key('kTitleBy1stLetter', substring(title_display,1,1) )[1] ) ]" &gt; &lt;xsl:variable name="v1st" select="substring(title_display,1,1)"/&gt; &lt;h2&gt;&lt;xsl:value-of select="$v1st"/&gt;&lt;/h2&gt; &lt;div class="{translate($v1st, $vUpper, $vLower)}-content"&gt; &lt;ul&gt; &lt;xsl:for-each select= "key('kTitleBy1stLetter',$v1st)"&gt; &lt;li&gt;&lt;xsl:value-of select="title_display"/&gt;&lt;/li&gt; &lt;/xsl:for-each&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/xsl:for-each&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p><strong>When applied on the originally provided XML document</strong>:</p> <pre><code>&lt;databases&gt; &lt;database&gt; &lt;title_display&gt;Aardvark&lt;/title_display&gt; &lt;/database&gt; &lt;database&gt; &lt;title_display&gt;Apple&lt;/title_display&gt; &lt;/database&gt; &lt;database&gt; &lt;title_display&gt;Blue&lt;/title_display&gt; &lt;/database&gt; &lt;database&gt; &lt;title_display&gt;Car&lt;/title_display&gt; &lt;/database&gt; &lt;/databases&gt; </code></pre> <p><strong>produces exactly the wanted result</strong>:</p> <pre><code>&lt;h2&gt;A&lt;/h2&gt; &lt;div class="a-content"&gt; &lt;ul&gt; &lt;li&gt;Aardvark&lt;/li&gt; &lt;li&gt;Apple&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;h2&gt;B&lt;/h2&gt; &lt;div class="b-content"&gt; &lt;ul&gt; &lt;li&gt;Blue&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;h2&gt;C&lt;/h2&gt; &lt;div class="c-content"&gt; &lt;ul&gt; &lt;li&gt;Car&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p><strong>Do note, that the Muenchian method is hugely more efficient than the O(N^2) solution</strong> that uses comparison of all <code>database</code> elements on the <code>preceding-sibling::</code> axis.</p> <p><strong>Also, this solution produces the <code>class</code> attributes value with the required capitalization</strong>.</p>
 

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