QDomDocument toString conversion issue

  • In the following example

    QDomDocument dom;
    QDomElement element= dom.createElement("MyElement");
    element.setAttribute("attr1", "foo");
    element.setAttribute("attr2", "bar");
    element.setAttribute("attr3", "<<statistics>> Integer status");
    QString text = dom.toString();
    qDebug() << QString("text = %1").arg(text);
    QFile outFile("C:/temp/testFile.dcf");
    if ( outFile.open(QIODevice::WriteOnly|QIODevice::Text))
      QTextStream stream( &outFile );
      stream << text << endl;

    The produced file will contain:

    <MyElement attr2="bar" attr1="foo" attr3="&lt;&lt;statistics>> Integer status"/>

    While I am awaiting it to contain:

    <MyElement attr2="bar" attr1="foo" attr3="<<statistics>> Integer status"/>

    Does anyone know how this could be addressed?

  • Qt Champions 2017

    Some characters must be escaped in XML documents

    "   &quot;
    '   &apos;
    <   &lt;
    >   &gt;
    &   &amp;


    It should turn into correct string once read back.


    element.setAttribute("attr3", "\<\<statistics\>\> Integer status");

    will work but I didnt test it.

  • Thanks for the reply.

    Well I could understand that some characters must be escaped, but I do not understand the logic behind Qt escaping some of them but not all.

    In my example I am passing the string: <<statistics>> Integer status
    Qt is escaping the '<' characters but not the '>' characters composing the string.

    Also your suggestion to write:

    element.setAttribute("attr3", "\<\<statistics\>\> Integer status");

    will not work for me. The code I gave here was just an example to show what I was observing. I am actually reading several XML files and use the content found in these files and combine those to create some new XML files. The "<<statistics>> Integer status" string is something I do find in the input XML files, and I would like to have this string appearing again in the XML files I am generating with my application.

  • Qt Champions 2017

    Well maybe you can use

    QString plain = "#include <QtCore>"
    QString html = plain.toHtmlEscaped();

    // html == "#include &lt;QtCore&gt;"

    it seems to be a known issue with QDomDocument that not all are automatically escaped but i didnt not find further info on why.

  • Is there a way to force the characters NOT to be escaped ?

  • Qt Champions 2017

    Not that I have seen.
    Also that would be invalid XML.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.