XSLT XML Question.
Looking into a simple transformation. I have simple index xml input. I have to output the the first and last element with a for each chapter. AS shown below. any help will be much appreciated.
Regards JJ
Input
<book>
<page number="1">Chapter01</page>
<page number="2">Chapter01</page>
<page number="3">Chapter01</page>
<page number="4">Chapter01</page>
<page number="5">Chapter01</page>
<page number="6">Chapter01</page>
<page number="7">Chapter02</page>
<page number="8">Chapter02</page>
<page number="9">Chapter02</page>
<page number="10">Chapter02</page>
<page number="11">Chapter02</page>
<page number="12">Chapter02</page>
<page number="13">Chapter03</page>
<page number="14">Chapter03</page>
<page number="15">Chapter03</page>
<page number="16">Chapter03</page>
<page number="17">Chapter03</page>
<page number="18">Chapter03</page>
</book>
Output
<book>
<page number="1">Chapter01</page>
<page number="6">Chapter01</page>
<page number="7">Chapter02</page>
<page number="12">Chapter02</page>
<page number="13">Chapter03</page>
<page number="18">Chapter03</page>
</book>
Updated to take advantage of a cleaner predicate – thanks to @SeanB.Durkin.
I. XSLT 1.0 Solution
When this XSLT:
…is applied to the original XML:
…the desired result is produced:
Explanation:
Muenchian Groupingto determine the unique<page>elements by their value.<page>element, two<page>elements are copied: the first and last from the group that contains the unique value.II. XSLT 2.0 Solution
Note that in XSLT 2.0, the solution becomes even simpler.
When this XSLT:
…is applied to the original XML, the same desired result is produced:
Explanation:
for-each-groupelement andcurrent-group()instruction are used.