Replace special characters in XSLT

There is a pure XSLT way to do this.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
    <xsl:variable name="vAllowedSymbols"
        select="'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'"/>
    <xsl:template match="node() | @*">
        <xsl:copy>
            <xsl:apply-templates select="node() | @*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="text()">
        <xsl:value-of select="
            translate(
                .,
                translate(., $vAllowedSymbols, ''),
                ''
                )
            "/>
    </xsl:template>
</xsl:stylesheet>

Result against this sample:

<t>
    <Name>O'Niel</Name>
    <Name>St Peter</Name>
    <Name>A.David</Name>
</t>

Will be:

<t>
    <Name>ONiel</Name>
    <Name>StPeter</Name>
    <Name>ADavid</Name>
</t>

Leave a Comment