[Qt-interest] Have QXmlStreameWriter write the encoding information

Lingfa Yang lingfa at brandeis.edu
Fri Jun 5 06:19:36 CEST 2009


Andreas Pakulat wrote:
> On 04.06.09 01:19:57, Aleksandar Lazic wrote:
>   
>> On Mit 03.06.2009 23:08, Andreas Pakulat wrote:
>>     
>>> In fact, Qt's XmlStreamReader won't read the result back in, see this
>>> example:
>>>
>>> ,----[ main.cpp ]-
>>> | #include <QtCore>
>>> | #include <QDebug>
>>> | #include <QtXml>
>>> | 
>>> | int main(int argc, char** argv)
>>> | {
>>> |     QString tmp;
>>> |     QXmlStreamWriter w(&tmp);
>>>       
>> Please can you try this:
>>     
>
> I know that works, I was proving to Lingfa that adding a PI that includes
> the encoding will still get you a broken XML if you use QString as output
> for the writer.
>
> Andreas
>
>   
No, it not true. No broken XML when  I use either QFile, QString, or 
QByteArray:
  {
    QFile file("test.xml");
    QString s;
    QString ba;

    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
      //QXmlStreamWriter w(&file); // 1
      QXmlStreamWriter w(&s);  // 2
      //QXmlStreamWriter w(&ba); // 3
      w.writeProcessingInstruction("xml", "version=\"1.0\" 
encoding=\"UTF-8\"");

      w.writeStartElement("test");
      w.writeCharacters("är");
      w.writeEndElement();
    }
    file.write(s.toUtf8()); // 2
    //file.write(ba.toUtf8()); // 3
    file.close();

    file.open( QIODevice::ReadOnly );
    QXmlStreamReader r(&file);
    while( !r.atEnd()) {
      r.readNext();
    }
    if (r.hasError()) {
      QString err = r.errorString();
    }
  }

I red your code where "broken xml" is generate because, first, you 
should not use:
     w.setCodec("ISO-8859-1");
which is not a supported encoding, at least, up to Qt4.5.0. Neither 
"ISO-8859-1" nor any of its possible aliases,"latin1", "CP819", 
"IBM819", and "iso-ir-100" is included in the supported encoding list.

Second, what does writeStartDocument("1.0"); mean? It will write out an 
processing instruction (PI) line. Then, if you call 
writeProcessingInstruction(), of course, you will get two PI lines.
You shouldn't call writeStartDocument() if you have 
writeProcessingInstruction() does the job.

Third, it seems the method fromUtf8() should be removed while writing an 
element content.

Lingfa







More information about the Qt-interest-old mailing list