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

[xsl] Merging adjacent elements


Subject: [xsl] Merging adjacent elements
From: "Rick Quatro rick@xxxxxxxxxxxxxx" <xsl-list-service@xxxxxxxxxxxxxxxxxxxxxx>
Date: Fri, 28 Aug 2015 21:25:10 -0000

I have this xml content:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <p>This is a <code>test</code> of <code><i>adjacent</i>
</code><code>code </code><code>elements</code> to see if we can merge
them.</p>
</root>

What I want to end up with is this:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <p>This is a <code>test</code> of <code><i>adjacent</i> code
elements</code> to see if we can merge them.</p>
</root>

Here is my XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">
    
    <xsl:output indent="yes"/>
    
    <xsl:template match="/">
        <xsl:apply-templates/>
    </xsl:template>
    
    <xsl:template match="p">
        <xsl:copy>
            <xsl:for-each-group select="*"
group-adjacent="boolean(self::code)">
                <xsl:choose>
                    <xsl:when test="current-grouping-key()">
                        <code>
                            <xsl:apply-templates
select="current-group()/node()"/>
                        </code> 
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:apply-templates select="current-group()"/>  
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:for-each-group>
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>
    
</xsl:stylesheet>

Here is my output:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <p>
       <code>test<i>adjacent</i> code elements</code>
   </p>
</root>

How do I get the rest of the <p> content from the input? Thanks in advance.

Rick


Current Thread
Keywords