Remove Duplicates from a list XSLT 1.0 based on element value

3.7k Views Asked by At

I need help with writing a function in xslt 1.0 that I can pass a list and it'll return the list with duplicates removed. It needs to be a template that I can easily clone or modify for other lists since there are several lists that I want to be able to run this.

Here is one example:

Input list:

 <Diagnoses>
      <Code>444.4</Code>
      <Code>959.99</Code>
      <Code>524</Code>
      <Code>444.4</Code>
    </Diagnoses>

Desired Output, after the duplicate code value 444.4 is removed:

 <Diagnoses>
    <Code>444.4</Code>
    <Code>959.99</Code>
    <Code>524</Code>
 </Diagnoses>

Here is what I have so far, but it doesn't seem to be working:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:math="http://exslt.org/math" 
xmlns:exsl="http://exslt.org/common" 
xmlns:data="http://example.com/data" version="1.0" 
extension-element-prefixes="math exsl" 
exclude-result-prefixes="math exsl data">
   <xsl:output omit-xml-declaration="yes" />






<xsl:variable name="DiagnosesList" select="Diagnoses"/>

<Diagnoses>
   <xsl:call-template name="DedupeLists">
      <xsl:with-param name="Input" select = "exsl:node-set($DiagnosesList)" />
    </xsl:call-template>
</Diagnoses>


<xsl:template name="DedupeLists">
    <xsl:param name = "Input" />

    <xsl:for-each select="$Input/*">
     <xsl:if test="Code[not(preceding::Code)]">
          <xsl:copy-of select="."/>
        </xsl:if>
     </xsl:for-each>

</xsl:template>   

</xsl:stylesheet>
2

There are 2 best solutions below

1
On BEST ANSWER

@lingamurthy,

Just

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:strip-space elements="*"/>
<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="Code[. = preceding-sibling::Code]"/>
</xsl:stylesheet>
0
On

This is one way:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:strip-space elements="*"/>
    <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="Code[not(. = preceding-sibling::Code)]">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Code"/>

</xsl:stylesheet>