John
John

Reputation: 1319

XSL Replace of characters ( )

I have a node with some data:

<something>Blah blah (Hello World) hihi</something>

When I perform an XSLt i am attempting to escape the open and close brackets and can not for the life of me work out how to achieve this so far I am attempting something like this.

<xsl:variable name="rb">(</xsl:variable>
<xsl:message><xsl:value-of select="replace(something, $rb, concat('\\', $rb))" /</xsl:message>

This is the error I am getting using Saxon:

Error at xsl:template on line 728 column 34 of something.xml: FORX0002: Error at character 1 in regular expression "(": expected ())

Upvotes: 4

Views: 23211

Answers (3)

imran
imran

Reputation: 461

<xsl:template match="text">
       <xsl:variable name="tex" select="' blabla ? blabl ?  abla ?  '"/>
       <xsl:element name="text">
           <xsl:value-of select="replace($tex,'\?','.')"/>
       </xsl:element>
   </xsl:template>

Upvotes: 0

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243569

This works with AltovaXML20011 (XML-SPY):

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>  
 <xsl:template match="/">
  <xsl:sequence select="replace(replace(., '\(', '\\(' ), '\)', '\\)' )"/>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document:

<something>Blah blah (Hello World) hihi</something>

the wanted result is produced:

Blah blah \(Hello World\) hihi

Upvotes: 3

FailedDev
FailedDev

Reputation: 26940

<xsl:variable name='string'>Blah blah (Hello World) hihi</xsl:variable>

<xsl:message>
  <xsl:value-of select="replace($string, '(\(|\))','\\$1')" />
</xsl:message>

This will work for either bracket. Your code is also incomplete. What is something? Does it contain the value you expect? You are missing a > at the end of xsl:value-of.

EDIT : After @Dimitre's comment :

<xsl:variable name="rb">(</xsl:variable>
<xsl:variable name='string'>Blah blah (Hello World) hihi</xsl:variable>

<xsl:message>
  <xsl:value-of select="replace($string, concat('\', $rb), concat('\\', $rb))" />
</xsl:message>

The above would have the results you originally wanted, although I see no reason to prefer this over my original solution.

Upvotes: 2

Related Questions