Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>This is a simpler more efficient XSLT 1.0 solution, than counting all preceding siblings</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:key name="kFollowing" match="item" use="generate-id(preceding-sibling::header[1])"/&gt; &lt;xsl:template match="/*"&gt; &lt;root&gt; &lt;xsl:apply-templates select="header"/&gt; &lt;/root&gt; &lt;/xsl:template&gt; &lt;xsl:template match="header"&gt; &lt;heather2&gt; &lt;xsl:copy-of select="key('kFollowing', generate-id())"/&gt; &lt;/heather2&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p><strong>When this transformation is applied on the following XML document</strong>:</p> <pre><code>&lt;root&gt; &lt;header/&gt; &lt;item&gt;1&lt;/item&gt; &lt;item&gt;2&lt;/item&gt; &lt;item&gt;3&lt;/item&gt; &lt;header/&gt; &lt;item&gt;5&lt;/item&gt; &lt;item&gt;6&lt;/item&gt; &lt;item&gt;7&lt;/item&gt; &lt;/root&gt; </code></pre> <p><strong>the wanted, correct result is produced</strong>:</p> <pre><code>&lt;root&gt; &lt;heather2&gt; &lt;item&gt;1&lt;/item&gt; &lt;item&gt;2&lt;/item&gt; &lt;item&gt;3&lt;/item&gt; &lt;/heather2&gt; &lt;heather2&gt; &lt;item&gt;5&lt;/item&gt; &lt;item&gt;6&lt;/item&gt; &lt;item&gt;7&lt;/item&gt; &lt;/heather2&gt; &lt;/root&gt; </code></pre> <p><strong>Explanation</strong>:</p> <p>A key is defined in such a way that for a <code>header</code> any of the immediately-following <code>item</code> elements is matched by the <code>generate-id()</code> of this <code>header</code>.</p> <p><strong>II. XSLT 2.0 solution</strong>:</p> <pre><code>&lt;xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:output omit-xml-declaration="yes" indent="yes"/&gt; &lt;xsl:template match="/*"&gt; &lt;root&gt; &lt;xsl:for-each-group select="item" group-adjacent= "generate-id(preceding-sibling::header[1])"&gt; &lt;header2&gt; &lt;xsl:sequence select="current-group()"/&gt; &lt;/header2&gt; &lt;/xsl:for-each-group&gt; &lt;/root&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p><strong>when this transformation is applied on the same XML document (above), the same correct result is produced</strong>:</p> <pre><code>&lt;root&gt; &lt;header2&gt; &lt;item&gt;1&lt;/item&gt; &lt;item&gt;2&lt;/item&gt; &lt;item&gt;3&lt;/item&gt; &lt;/header2&gt; &lt;header2&gt; &lt;item&gt;5&lt;/item&gt; &lt;item&gt;6&lt;/item&gt; &lt;item&gt;7&lt;/item&gt; &lt;/header2&gt; &lt;/root&gt; </code></pre> <p><strong>Explanation</strong>: Use of <code>xsl:for-each-group</code>, <code>group-adjacent</code>, <code>current-group()</code></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