Search code examples
javascriptxmlreplacecdata

How to replace "&" within CDATA in XML to interpret in Java Script (ECMAScript for XML)


var newstring = srchStr3.replace(/&/g, "&");


var srchStr3 = job.getJobInfo("JobData").replace("&", "&");

These are some snipnets I tried which could not fix the issue


Solution

  • I'm guessing that you have some JavaScript code embedded in XML that is inappropriately escaped. (If that is not the case please edit your question.)

    You wouldn't need to have to do this in JS (nor do I think it's actually feasible) if your JS code was within CDATA, e.g.:

    <code>
      <![CDATA[
        function foo(a, b) {
          return a && b;
        }
      ]]>
    </code>
    

    When you process the XML make sure the output is text. With XSL for example:

    <?xml version="1.0"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
      <xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
    
      <xsl:template match="/code">
        <xsl:value-of select="."/>
      </xsl:template>
    
    </xsl:stylesheet>
    

    Which produces this output:

    $ xsltproc ~/Desktop/so.xsl ~/Desktop/so.xml 
    
    
        function foo(a, b) {
          return a && b;
        }