Re: [xsl] merging the contents of consecutive duplicate elements

Subject: Re: [xsl] merging the contents of consecutive duplicate elements
From: Mukul Gandhi <gandhi.mukul@xxxxxxxxx>
Date: Tue, 18 Oct 2005 19:30:17 +0530
Please try this stylesheet(XSLT 1.0). It merges same consecutive
elements into one element. I am assuming you will have only element
nodes as children of <info>(or whatever element at this level). I also
enclosed your XML in a <root> tag to make it well formed.

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
version="1.0">

<xsl:output method="xml" indent="yes" />

<xsl:template match="/root">
  <root>
    <xsl:for-each select="*[not(name(preceding-sibling::*[1]) = name())]">
      <xsl:element name="{name()}">
        <xsl:copy-of select="*" />
        <xsl:call-template name="makegroup">
          <xsl:with-param name="name" select="name()" />
          <xsl:with-param name="list" select="following-sibling::*" />
        </xsl:call-template>
      </xsl:element>
    </xsl:for-each>
  </root>
</xsl:template>

<xsl:template name="makegroup">
  <xsl:param name="name" />
  <xsl:param name="list" />

  <xsl:if test="$name = name($list[1])">
    <xsl:copy-of select="$list[1]/*" />
    <xsl:call-template name="makegroup">
      <xsl:with-param name="name" select="$name" />
      <xsl:with-param name="list" select="$list[position() &gt; 1]" />
    </xsl:call-template>
  </xsl:if>
</xsl:template>

</xsl:stylesheet>

Regards,
Mukul


On 10/18/05, Annmarie Rubin (anrubin) <anrubin@xxxxxxxxx> wrote:
> Hello list,
>
> I haven't found this in the archives. I have XML that can contain
> duplicate, consecutive elements with different contents, for example:
>
> <info>
>      <para>text A </para>
>      <note>note A </note>
>  </info>
>  <info>
>      <para>text B</para>
>      <note>note B</note>
>      <para>text C</para>
>  </info>
>
> Is there a way to do the following:
>
> merge the contents of the duplicate elements into a single info element,
> for example:
>
> <info>
>    <para>text A</para>
>    <note>note A</note>
>    <para>text B</para>
>    <note>note B</note>
>    <para>text C</para>
> </info>
>
> Thanks,
>
> Ann Marie

Current Thread