[XSL-LIST Mailing List Archive Home] [By Thread] [By Date]

[xsl] Merging adjacent nodes of same type


Subject: [xsl] Merging adjacent nodes of same type
From: Matt Sims <mattsims@xxxxxxxxxxxxx>
Date: Fri, 23 Sep 2005 11:16:06 +0100

Hi,

I have some XML that includes following snippet:

<text>
   <offset x="1" y="2" z="3" />
   Some text
   <offset x="4" y="5" z="6" />
   <offset x="7" y="8" z="9" />
   Some more text
</text>

I wish to merge any adjacent empty 'offset' nodes and sum the attribute
values, i.e. to give the following result:

<text>
   <offset x="1" y="2" z="3" />
   Some text
   <offset x="11" y="13" z="15" />
   Some more text
</text>

The 'offset' nodes may contain child nodes/text, but I only want to
merge adjacent offset nodes that do not have any children or text, so
the following snippet:

<text>
   <offset x="1" y="2" z="3" />
   Some text
   <offset x="4" y="5" z="6" />
   <offset x="7" y="8" z="9" />
   Some more text
   <offset x="10" y="11" z="12">
       Yet some more text
   </offset>
   <offset x="13" y="14" z="15">
       And finally some more text
   </offset>
</text>

would result in:

<text>
   <offset x="1" y="2" z="3" />
   Some text
   <offset x="11" y="13" z="15" />
   Some more text
   <offset x="10" y="11" z="12">
       Yet some more text
   </offset>
   <offset x="13" y="14" z="15">
       And finally some more text
   </offset>
</text>

I have previously performed a similar exercise on nested 'indent' nodes
of the same type using the following template:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:aston="http://www.aston.tv/schemas/Aston/Aston7">

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

   <xsl:template match="aston:indent[aston:indent and count(node())=1]">
       <xsl:element name="indent" namespace="{namespace-uri()}">
           <xsl:attribute name="x">
               <xsl:value-of select="@x + aston:indent/@x"/>
           </xsl:attribute>
           <xsl:attribute name="y">
               <xsl:value-of select="@y + aston:indent/@y"/>
           </xsl:attribute>
           <xsl:attribute name="z">
               <xsl:value-of select="@z + aston:indent/@z"/>
           </xsl:attribute>
           <xsl:apply-templates select="*/node()"/>
       </xsl:element>
   </xsl:template>

</xsl:stylesheet>

But I think I need to use a 'foreach' loop for this problem in
association with 'group-adjacent', which I have no experience of.

Thanks in advance for any help you can give me.

Regards,

Matt.


Current Thread
Keywords