xsl-list
[Top] [All Lists]

Re: [xsl] Merging like Siblings within a variable as="element()*"

2010-08-20 10:07:40
Alex Muir wrote:
Hi,

I've been using the following code that works based on templates to
merge <chunk> siblings beside one another such that the following

<chunk>1</chunk>
<chunk>2</chunk>
<notChunk>3</notChunk>
<chunk>4</chunk>
<chunk>5</chunk>

would be merged to

<chunk>12</chunk>
<notChunk>3</notChunk>
<chunk>45</chunk>

Here is the code:
<xsl:template match="chunk" priority="1">
    <xsl:copy>
      <xsl:copy-of select="@*"/>
      <xsl:copy-of select="text()"/>
      <xsl:apply-templates
        select="following-sibling::*[1][self::chunk]"
        mode="more"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="chunk[preceding-sibling::*[1][self::chunk]]"
priority="2"/>

   <xsl:template match="chunk" mode="more">
    <xsl:copy-of select="text()"/>
    <xsl:apply-templates
       select="following-sibling::*[1][self::chunk]"
      mode="more"/>
  </xsl:template>


This works great if I'm applying the templates to an xml file however
I'm interested to have the chunks within a <xsl:variable
name="content" as="element()*> and then merge them and output them and
I'm not sure how to go about merging the like siblings within a
variable.

Any suggestions are highly appreciated?

The as="element()*" suggests you are using XSLT 2.0, then I am astonished you are not using xsl:for-each-group group-adjacent from the beginning.
Are you using XSLT 2.0? Can't you use
<xsl:for-each-group select="$your-variable" group-adjacent="boolean(self::chunk)">
     <xsl:choose>
       <xsl:when test="current-grouping-key()">
<chunk><xsl:value-of select="current-group()" separator=""/></chunk>
       </xsl:choose>
       <xsl:otherwise>
         <xsl:copy-of select="current-group()"/>
       </xsl:otherwise>
     </xsl:choose>
  </xsl:for-each-group>

--

        Martin Honnen
        http://msmvps.com/blogs/martin_honnen/

--~------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--

<Prev in Thread] Current Thread [Next in Thread>