Sam
Sam

Reputation: 841

How to merged continued multiple elements in single element -XSLT

I have found continued multiple different elements (e.g. span, italic) in the p element. span continued elements merged in single element but how to handle continued multiple italic element.
Input XML

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

XSLT Code

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

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

Expected Output

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

Upvotes: 0

Views: 44

Answers (1)

zx485
zx485

Reputation: 29022

You can change your second template by using the local-name()s of the elements like this:

<xsl:template match="p">
    <xsl:copy>
        <xsl:for-each-group select="node()" group-adjacent="local-name()='span' or local-name()='italic'">
            <xsl:choose>
                <xsl:when test="current-grouping-key()">
                    <xsl:copy>
                        <xsl:apply-templates select="current-group()/node()"/>
                    </xsl:copy>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:apply-templates select="current-group()"/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each-group>
    </xsl:copy>
</xsl:template>

The output is

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

The output may be formatted differently.

Upvotes: 1

Related Questions