I have a simple XML with two levels (Header and Line) of tags such as:
<?xml version="1.0"?>
<Header>
<line>Line 1</line>
<line>Line 2</line>
<line>Line 3</line>
<line>Line 4</line>
<line>Line 5</line>
<line>Line 6</line>
<line>Line 7</line>
<line>Line 8</line>
<line>Line 9</line>
</Header>
I need to group the lines on sets of X (X=3 for example) lines so that my output is the following:
<?xml version="1.0"?>
<Header>
<set>
<line>Line 1</line>
<line>Line 2</line>
<line>Line 3</line>
</set>
<set>
<line>Line 4</line>
<line>Line 5</line>
<line>Line 6</line>
</set>
<set>
<line>Line 7</line>
<line>Line 8</line>
<line>Line 9</line>
</set>
</Header>
How do I write a XSLT that can do this kind of transformation?
Thanks!
O
http://www.xml.com/pub/a/2003/11/05/tr.html shows a slightly less ugly way of doing this using XSLT 2.0. The key element is this one:
<xsl:for-each-group select="*" group-ending-with="*[position() mod 3 = 0]">
The following transformation produces the required result:
When applied on the provided XML document:
the result is:
Do note the following:
The use of the XPath
mod
operator to find out the firstline
element in every group ofvN
elements.The use of modes, in order to be able to process different
line
elements by different templatesThat should be possible. Has the desired output:
(The $pos-1, $pos-2 thing is not very pretty)
In general in XSLT if you want to create a heirarchy from a list you can make use of the preceding-sibling and following-sibling keywords. This is easist if there is a marker entry between sets.
As you don't have a marker as such in this case I imagine a solution could involve the following-sibling keyword and the mod operator. The mod providing the division between sets.
I haven't tried it but that would be my first start.
xslt is normally a good place to start with understanding the different keywords.