I’m working with XSLT 1.0 from PHP and want to wrap all the sibling elements after a heading (h2) into a div so I can toggle them.
The input would look like
...
<h2>Nth title</h2>
<first child>...</first child>
...
<last child>...</last child>
<h2>N+1st title</h2>
...
and the output should be
...
<h2>Nth title</h2>
<div>
<first child>...</first child>
...
<last child>...</last child>
</div>
<h2>N+1st title</h2>
...
Is there a way to do this in XSLT 1.0?
This transformation:
when applied on this XML document:
produces the wanted, correct result:
Explanation:
The identity rule/template copies every node “as-is”.
The identity rule is overriden for
h2elements. Here the action is to copy theh2element and then to output adivand inside it to apply templates (in a special mode) to all nodes (that are noth2themselves) for which thish2element is the first preceding-siblingh2element.The nodes to include in the previous step are conveniently defined as an
<xsl:key>instruction.In order to stop the nodes that are wrapped in
divto be output again by the identity rule, we provide a template matching such nodes, that simply ignores them.