Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>This solution is a little bit simpler, more efficient and at the same time more general</strong> than the one presented by Richard:</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;!-- --&gt; &lt;xsl:key name="kFileByVal" match="File" use="." /&gt; &lt;!-- --&gt; &lt;xsl:key name="kDescByFile" match="Description" use="../File"/&gt; &lt;!-- --&gt; &lt;xsl:template match="/*"&gt; &lt;html&gt; &lt;body&gt; &lt;xsl:for-each select= "*/File[generate-id() = generate-id(key('kFileByVal',.)[1])]"&gt; &lt;h1&gt;&lt;xsl:value-of select="."/&gt;&lt;/h1&gt; &lt;xsl:for-each select="key('kDescByFile', .)"&gt; &lt;p&gt;&lt;xsl:value-of select="."/&gt;&lt;/p&gt; &lt;/xsl:for-each&gt; &lt;/xsl:for-each&gt; &lt;/body&gt; &lt;/html&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p><strong>when applied to the provided XML document</strong>:</p> <pre><code>&lt;Problems&gt; &lt;Problem&gt; &lt;File&gt;file1&lt;/File&gt; &lt;Description&gt;desc1&lt;/Description&gt; &lt;/Problem&gt; &lt;Problem&gt; &lt;File&gt;file1&lt;/File&gt; &lt;Description&gt;desc2&lt;/Description&gt; &lt;/Problem&gt; &lt;Problem&gt; &lt;File&gt;file2&lt;/File&gt; &lt;Description&gt;desc1&lt;/Description&gt; &lt;/Problem&gt; &lt;/Problems&gt; </code></pre> <p><strong>Produces the wanted result</strong>:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;h1&gt;file1&lt;/h1&gt; &lt;p&gt;desc1&lt;/p&gt; &lt;p&gt;desc2&lt;/p&gt; &lt;h1&gt;file2&lt;/h1&gt; &lt;p&gt;desc1&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>Do note</strong> the simple match pattern of the first <a href="http://www.w3.org/TR/xslt#key" rel="noreferrer"><strong><code>&lt;xsl:key&gt;</code></strong></a> and how, using a second <code>&lt;xsl:key&gt;</code>, we locate all "<code>Description</code>" elements that are siblings of a "<code>File</code>" element that has a given value.</p> <p>We could have used more templates instead of <a href="http://www.w3.org/TR/xslt#for-each" rel="noreferrer"><strong><code>&lt;xsl:for-each&gt;</code></strong></a> pull-processing, however this is a quite simple case and the solution really benefits from shorter, more compact and more readable code.</p> <p><strong>Also note, that in <a href="http://www.w3.org/TR/xslt20/" rel="noreferrer">XSLT 2.0</a> one will typically use the <a href="http://www.w3.org/TR/xslt20/#xsl-for-each-group" rel="noreferrer"><code>&lt;xsl:for-each-group&gt;</code></a> instruction</strong> instead of the <a href="http://dpawson.co.uk/xsl/sect2/N4486.html#d6060e85" rel="noreferrer"><strong>Muenchian method</strong></a>.</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