Remove duplicate XML elements using XSLT

February 20, 2015 ・0comments

Today I faced an issue where I am receiving a XML message with duplicate elements. So I wanted to remove those duplicate elements using some condition . For that I came up with a XSLT which does that.

My XML input:

<OurGuestsCollection xmlns="http://ws.wso2.org/dataservice">
    <OurGuests>
        <id>2</id>
        <firstname>Sample</firstname>
        <lastname>Sample</lastname>
        <email>One</email>
        <reg_date>2015-02-18T13:59:43.000+05:30</reg_date>
    </OurGuests>
    <OurGuests>
        <id>3</id>
        <firstname>Sample1</firstname>
        <lastname>Sample1</lastname>
        <email>One</email>
        <reg_date>2015-02-18T14:13:18.000+05:30</reg_date>
    </OurGuests>
    <OurGuests>
        <id>4</id>
        <firstname>Sample1</firstname>
        <lastname>Sample1</lastname>
        <email>One1</email>
        <reg_date>2015-02-18T14:16:21.000+05:30</reg_date>
    </OurGuests>
</OurGuestsCollection>

XSLT:

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>

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

    <xsl:template match="m0:OurGuests"
        xmlns:m0="http://ws.wso2.org/dataservice">
        <xsl:if test="not(following::m0:OurGuests[m0:firstname=current()/m0:firstname])">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

XML Output :

<OurGuestsCollection xmlns="http://ws.wso2.org/dataservice">
    <OurGuests>
        <id>2</id>
        <firstname>Sample</firstname>
        <lastname>Sample</lastname>
        <email>One</email>
        <reg_date>2015-02-18T13:59:43.000+05:30</reg_date>
    </OurGuests>

    <OurGuests>
        <id>4</id>
        <firstname>Sample1</firstname>
        <lastname>Sample1</lastname>
        <email>One1</email>
        <reg_date>2015-02-18T14:16:21.000+05:30</reg_date>
    </OurGuests>
</OurGuestsCollection>

Post a Comment