Brice
Brice

Reputation: 67

XSLT translate backslash to double backslash

I need to transform this value:

    <MediaFile>F:\DEMO\TEST\HELLO.pm4</MediaFile>

to this:

<MediaFile>F:\\DEMO\\TEST\\HELLO.pm4</MediaFile>

I have tried a lot of thing, translate, concat, substring and replace but I didn't succeeded.

Here's precisely, what I've tried:

Source file:

        <?xml version="1.0" encoding="UTF-8" ?>
<Asset version="1.0">
    <Target>
    <Name>HELLO</Name>
    <MediaFile>F:\DEMO\TEST\HELLO.mp4</MediaFile>

</Target>
</Asset>

XSLT:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xsl:output method="text" indent="yes" encoding="UTF-8"/>
    <xsl:template match="/">

        <xsl:variable name="MediaFile">
            <xsl:value-of select="Asset/Target/MediaFile"/>
        </xsl:variable>

        <xsl:variable name="Media">
            <xsl:value-of select="replace($MediaFile,'\','\\')"/>
        </xsl:variable> 

            <xsl:element name="Media">
                <xsl:value-of select="$Media"/>
            </xsl:element>  
        </xsl:template>
</xsl:stylesheet>

I'm using xslt 2.0

Any idea? Thanks

Upvotes: 1

Views: 2485

Answers (1)

Aniket V
Aniket V

Reputation: 3247

You would need to replace the below

<xsl:value-of select="replace($MediaFile,'\','\\')"/>

with

<xsl:value-of select="replace($MediaFile,'\\','\\\\')" />

In many programming languages, backslash is used to as an escape character to indicate the character following it needs special treatment. In this case, you would need to escape the character being replaced \ with \\ and also need to replace \\ with \\\\ (two backslashes).

Following question would help provide some detail explanation What does back slash "\" really mean?

Additionally, in the template that you have shared, the desired output is text, so there is no need to create an element named Media as it would come into picture if the desired output is XML. So the template code can be optimized as

<xsl:template match="/">
    <xsl:value-of select="replace(Asset/Target/MediaFile,'\\','\\\\')" />
</xsl:template>

Output

F:\\DEMO\\TEST\\HELLO.mp4

Upvotes: 3

Related Questions