Is there any function in QT to escape string for saving it in XML and decode it back after loading from XML ?
Is there any function in QT to escape string for saving it in XML and decode it back after loading from XML ?
Could you give more details on your problem? Have you tried using a CDATA section?
I have user-provided string which I want to save into XML file and then read it again. In order to do it I should replace some characters (at least <>&, may be others?) by coresponging XML entities.
Some strings are two short (object names) and there are too many of them to use CDATA. And even for CDATA I should somehow replace "]]>" sequence, shouldn't I ?
May be the problem is not clearly Qt-related, but as Qt has XML parsers I've thought it can also has such a function.
The simplest way is to base64 encode the string you want to store. Or you can do it properly by reencoding xml entities, but I think you'd have to do that manually.
I found 2 possible solutions:
1) encode/decode the text with the static functions
QUrl::toPercentEncoding()
QUrl::fromPercentEncoding()
You can specify what characters must be encoded and what not. You can simply make it encode "<", ">" and "&".
Qt Code:
// Original text // Encode it // --> encoded == "%3Ctext%3E" // Decode it // --> decoded == "<text>"To copy to clipboard, switch view to plain text mode
2) use the new QXmlStreamWriter class which generates XML files, automatically encoding what is needed
See QXmlStreamWriter::writeCharacters() and QXmlStreamWriter::writeCDATA().
Last edited by iw2nhl; 10th July 2007 at 19:36.
This seems to be exactly what I need ! Thanks a lot.2) use the new QXmlStreamWriter class which generates XML files, automatically encoding what is needed
See QXmlStreamWriter::writeCharacters() and QXmlStreamWriter::writeCDATA().
Probably it was overlooked by me and others since it has appeared only in 4.3
You do not want to do what the others have suggested. Use these routines for your DomElement, ect values.
Qt Code:
QString EncodeXML ( const QString& encodeMe ) { QString temp; for (quint32 index(0); index < encodeMe.size(); index++) { switch (character.unicode()) { case '&': temp += "&"; break; case '\'': temp += "'"; break; case '"': temp += """; break; case '<': temp += "<"; break; case '>': temp += ">"; break; default: temp += character; break; } } return temp; } QString DecodeXML ( const QString& decodeMe ) { temp.replace("&", "&"); temp.replace("'", "'"); temp.replace(""", "\""); temp.replace("<", "<"); temp.replace(">", ">"); return temp; }To copy to clipboard, switch view to plain text mode
If you use toPercentEncoding or...base64 encoding, who can read the xml that you have created? One of the benefits of XML is being able to read it from a text editor. Don't give up that advantage.
hispeedsurfer (31st January 2022)
Bookmarks