htmlc++qthtml-escape-charactersqtxml

How do I not escape HTML special characters in QDomText?


I'm trying to create an HTML document containing Javascript using Qt XML. Here is the relevant part of my Qt code:

QDomDocument document;
//Create head, body, etc
QDomElement script = document.createElement("script");
script.setAttribute("type", "text/javascript");
body.appendChild(script);    //body is the QDomElement representing the <body> tag
QDomText scriptText = document.createTextNode("if(x < 0){\n/*do something*/\n}");
script.appendChild(scriptText);

QFile file("C:\\foo.html");
file.open(QIODevice::WriteOnly);
QTextStream stream(&file);
stream << document.toString();

The problem is that in the Javascript code, it's escaping the < character replacing it with &lt;, giving the following output which isn't valid Javascript:

<script type="text/javascript">
    if(x &lt; 0){
        /*do something*/
    }
</script>

I've searched the Qt documentation for a solution, but haven't found anything.

A workaround could be to replace &lt; with < when writing in the file by doing stream << document.toString().replace("&lt;", "<"), but there might also be occurrences of &lt; outside of the Javascript code that I want to leave alone.

I can also think of a few Javascript tricks to check if a number is negative without using any special HTML characters, like for example if(String(x).indexOf('-') != -1), but I would like to know if there is a better way of doing it.

My question is how do I create a QDomText object with text containing special HTML characters like <, >, &, etc without them being escaped in QDomDocument::toString()?


Solution

  • You can put the javascript code in a CDATA section:

      QDomElement script = document.createElement("script");
      script.setAttribute("type", "text/javascript");
      body.appendChild(script);
    
      QString js = "if(x < 0){\n/*do something*/\n}";
      QDomCDATASection data = document.createCDATASection(js);
      script.appendChild(data);
    

    then remove the unwanted text right after:

      QString text = document.toString();
      text.replace("<![CDATA[", "\n");
      text.replace("]]>", "\n");