Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace a double quote with string ' \" ' in XSLT?

Tags:

xml

xslt

I have an XML in which the double quotes should be replaced with the string \".

eg:<root><statement1><![CDATA[<u>teset "message"here</u>]]></statement1></root>

so the output should be <root><statement1><![CDATA[<u>teset \"message\"here</u>]]></statement1></root>

Can anybody explain how to accomplish this?

like image 578
Tom Cruise Avatar asked Oct 16 '25 13:10

Tom Cruise


1 Answers

I. XSLT 1.0 solution:

This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"
 cdata-section-elements="statement1"/>
 <xsl:strip-space elements="*"/>

 <xsl:param name="pPattern">"</xsl:param>
 <xsl:param name="pReplacement">\"</xsl:param>

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match="statement1/text()" name="replace">
  <xsl:param name="pText" select="."/>
  <xsl:param name="pPat" select="$pPattern"/>
  <xsl:param name="pRep" select="$pReplacement"/>

 <xsl:choose>
  <xsl:when test="not(contains($pText, $pPat))">
   <xsl:copy-of select="$pText"/>
  </xsl:when>
  <xsl:otherwise>
   <xsl:copy-of select="substring-before($pText, $pPat)"/>
   <xsl:copy-of select="$pRep"/>
   <xsl:call-template name="replace">
    <xsl:with-param name="pText" select=
         "substring-after($pText, $pPat)"/>
    <xsl:with-param name="pPat" select="$pPat"/>
    <xsl:with-param name="pRep" select="$pRep"/>
   </xsl:call-template>
  </xsl:otherwise>
 </xsl:choose>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document:

<root>
    <statement1><![CDATA[<u>teset "message"here</u>]]></statement1>
</root>

produces the wanted, correct result:

<root>
   <statement1><![CDATA[<u>teset \"message\"here</u>]]></statement1>
</root>

II. XSLT 2.0 solution:

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <xsl:output omit-xml-declaration="yes" indent="yes"
 cdata-section-elements="statement1"/>

 <xsl:param name="pPat">"</xsl:param>
 <xsl:param name="pRep">\\"</xsl:param>

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

  <xsl:template match="statement1/text()">
   <xsl:sequence select="replace(.,$pPat, $pRep)"/>
  </xsl:template>
</xsl:stylesheet>

when applied on the same XML document (as above), the same correct result is produced:

<root>
      <statement1><![CDATA[<u>teset \"message\"here</u>]]></statement1>
</root>
like image 130
Dimitre Novatchev Avatar answered Oct 19 '25 09:10

Dimitre Novatchev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!