Tyler Darden
Tyler Darden

Reputation: 13

XSLT replace non ascii with space

I have made this XSLT but just removes non-ASCII characters.

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:param name="charset" select="'@.1234567890 abcdefghilmnopqrstuvwzkyx ABCDEFGHILMNOPQRSTUVWZYKX'" />

<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(., $charset, ''), '')"/>
</xsl:template>

</xsl:stylesheet>

I would like to replace instead with a simple space. Any clue?

Upvotes: 0

Views: 797

Answers (1)

Tim C
Tim C

Reputation: 70638

If there is a maximum length of the text you will be replacing, you can simply define a variable consisting of 150 spaces, and use that in the translate expression.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:strip-space elements="*"/>

    <xsl:param name="charset" select="'@.1234567890 abcdefghilmnopqrstuvwzkyx ABCDEFGHILMNOPQRSTUVWZYKX'" />
    <!-- 150 spaces -->
    <xsl:param name="spaces" select="'                                                                                                                                                      '" />

    <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(., $charset, ''), $spaces)"/>
    </xsl:template>
</xsl:stylesheet>

If you could use XSLT 2.0, you could use the replace function, which allows for regular expressions.

Upvotes: 3

Related Questions