View Full Version : How can I read an xml utf-16 file with QXmlStreamReader?

31st July 2012, 12:38
I try to find a way to read an xml file that has utf-16 encoding, apparently QIODevice can’t read utf-16 xml files, it says it’s invalid file.
After searching the internet and the t assistant I found that the only library that can set a codec in a file is QTextStream.
Then I found this: QTextCodec.
After searching a bit more on the internet I understood that I need to create an encoding function by myself that should look like this:

QByteArray myEncoderFunc( const QString &xmlfileNameSt );

And call this function like this:

xmlFile.setEncodingFunction ( myEncoderFunc ) ;

With all this information I don’t really know how do I make my file readable for QXmlStreamReader.

Can you help in this?


1st August 2012, 09:56
A file is just a stream of bytes to a QIODevice.

This code:

#include <QtCore>
#include <QDebug>

int main(int argc, char **argv)
QCoreApplication app(argc, argv);

QFile in("utf16test.xml");
QXmlStreamReader xml(&in);
while (!xml.atEnd()) {
qDebug() << xml.name();
if (xml.hasError()) {
// do error handling

return 0;

handles UTF16 encoded XML files just fine here. The reader code includes detection of UTF 16 or 32, BE or LE, with or without BOM, and falls back to UTF-8 based on the first four bytes of the XML file.