Using XSLT to remove duplicate entires in a simple XML file

duplicates, xml, xslt

Solution

The following XSLT should answer your question :

    <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="lang[@name=following-sibling::lang/@name]"/>
</xsl:stylesheet>

This way, you filter every `lang` element that have a following sibling `lang` element with the same value for the `name` attribute.

Problem

I am new to XSLT and am having a problem with removing duplicates from a simple XML file. Spent a lot of time trying to get it but it's never quite right. Here is the source file: ``` <?xml version="1.0" encoding="UTF-16"?> <language> <lang name="welcome">welcom</lang> <lang name="open">Open</lang> <lang name="close">Close</lang> <lang name="welcome">Welcome</lang> <lang name="copy">Copy</lang> </language> ``` Desired output is this: ``` <?xml version="1.0" encoding="UTF-16"?> <language> <lang name="open">Open</lang> <lang name="close">Close</lang> <lang name="welcome">Welcome</lang> <lang name="copy">Copy</lang> </language> ``` The actual files are much larger than this and "lang" and "name" may change later in the file, and I only want to keep the last duplicate. Basically, if the tag and attributes are duplicated, only keep the last entry. I hope this is possible with XSLT 1.0. If not, I can always use multiple scripts in case lang does change to something else. Thank you in advance!

Original source