Search code examples
xsltxslt-2.0

Continue Multiple span text merged in single span - XSLT


How to continued multiple spanelement the S/B merged in single span element.
Input XML

<root>
    <p>Paragraph <span>a</span><span>b</span><span>c</span><span>d</span> Under Continuing <span>Court</span> Jurisdiction</p>
    <p>Paragraph <span>a</span><span>b</span><span>c</span><span>d</span> Under Continuing Court <span>Jurisdiction</span></p>
</root>

Expected Output

<root>
    <p>Paragraph <span>abcd</span> Under Continuing <span>Court</span> Jurisdiction</p>
    <p>Paragraph <span>abcd</span> Under Continuing Court <span>Jurisdiction</span></p>
</root>

XSLT Code

        <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="span">
    <xsl:copy>
        <xsl:apply-templates/>
        <xsl:for-each select="following-sibling::*[1][self::span]">
            <xsl:value-of select="."/>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

Solution

  • The template for p elements should be along the lines of

     <xsl:template match="p">
            <xsl:copy>
                <xsl:for-each-group select="node()" group-adjacent=". instance of element(span)">
                    <xsl:choose>
                        <xsl:when test="current-grouping-key()">
                            <span>
                                <xsl:apply-templates select="current-group()/node()"/>
                            </span>
                        </xsl:when>
                        <xsl:otherwise>
                            <xsl:apply-templates select="current-group()"/>
                        </xsl:otherwise>
                    </xsl:choose>
                </xsl:for-each-group>
            </xsl:copy>
        </xsl:template>