Pairing Elements XSLT
Posted: Thu Mar 27, 2008 2:44 am
Hi,
I'm trying to write a transformation that takes repeating elements and places them in pairs and in order in the XML output. I want to convert this:
into:
My current XSLT finds each element and pairs it with its following-sibling but because it processes each node I get a
<double_module><para>Para 1</para><para>Para 2</para></double_module> and a <double_module><para>Para 2</para><para>Para 3</para></double_module>
Any assistance is greatly appreciated.
Thanks,
Bay
I'm trying to write a transformation that takes repeating elements and places them in pairs and in order in the XML output. I want to convert this:
Code: Select all
<Root>
<heading>Chapter 1</heading>
<module>
<para>Para 1</para>
</module>
<module>
<para>Para 2</para>
</module>
<module>
<para>Para 3</para>
</module>
<module>
<para>Para 4</para>
</module>
<module>
<para>Para 5</para>
</module>
<heading>Chapter 2</heading>
<module>
<para>Para 6</para>
</module>
<module>
<para>Para 7</para>
</module>
<module>
<para>Para 8</para>
</module>
</Root>
Code: Select all
<Root>
<heading>Chapter 1</heading>
<double_module>
<para>Para 1</para>
<para>Para 2</para>
</double_module>
<double_module>
<para>Para 3</para>
<para>Para 4</para>
</double_module>
<module>
<para>Para 5</para>
</module>
<heading>Chapter 2</heading>
<double_module>
<para>Para 6</para>
<para>Para 7</para>
</double_module>
<module>
<para>Para 8</para>
</module>
<heading>Chapter 3</heading>
</Root>
<double_module><para>Para 1</para><para>Para 2</para></double_module> and a <double_module><para>Para 2</para><para>Para 3</para></double_module>
Code: Select all
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output indent="yes"/>
<xsl:template match="Root">
<lesson>
<xsl:apply-templates/>
</lesson>
</xsl:template>
<xsl:template match="para">
<xsl:copy-of select="."/>
</xsl:template>
<xsl:template match="heading">
<xsl:copy-of select="."/>
</xsl:template>
<xsl:template match="module">
<xsl:choose>
<xsl:when test="following-sibling::*[1][self::module]"> <double_module>
<xsl:apply-templates/>
<xsl:apply-templates mode="in-module"
select="following-sibling::*[1][self::module]"/>
</double_module>
</xsl:when>
<xsl:otherwise>
<module>
<xsl:apply-templates/>
</module>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="module" mode="in-module">
<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>
Thanks,
Bay