Search code examples
xmlxsltxslt-1.0fxsl

How to extract unique characters from a string using XSLT 1.0?


one of the toughest challenges I have ever faced in XSLT designing ..

How to copy the unique characters in a given string ..
Test xml is:

<root>
<string>aaeerstrst11232434</string>
</root>

The output I am expecting is:

<string>aerst1234</string>

Solution

  • Here is an XSLT 1.0 solution, shorter than the currently selected answer and easier to write as it uses the str-foldl template of FXSL.

    <xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     xmlns:f="http://fxsl.sf.net/"
     exclude-result-prefixes="f">
    
     <xsl:import href="str-foldl.xsl"/>
     <xsl:output method="text"/>
    
     <f:addUnique/>
    
     <xsl:variable name="vFunAddunique" select=
      "document('')/*/f:addUnique[1]
      "/>
    
        <xsl:template match="string">
          <xsl:call-template name="str-foldl">
            <xsl:with-param name="pFunc" select="$vFunAddunique"/>
            <xsl:with-param name="pA0" select="''"/>
            <xsl:with-param name="pStr" select="."/>
          </xsl:call-template>
        </xsl:template>
    
        <xsl:template match="f:addUnique" mode="f:FXSL">
          <xsl:param name="arg1"/>
          <xsl:param name="arg2"/>
    
          <xsl:value-of select="$arg1"/>
          <xsl:if test="not(contains($arg1, $arg2))">
           <xsl:value-of select="$arg2"/>
          </xsl:if>
        </xsl:template>
    </xsl:stylesheet>
    

    When the above transformation is applied to the originally provided source XML document:

    <root>
        <string>aaeerstrst11232434</string>
    </root>
    

    the wanted result is produced:

    aerst1234
    

    Read more about FXSL 1.x (for XSLT 1.0) here, and about FXSL 2.x (for XSLT 2.0) here.