How to set the encoding of a XML file in Qt?

I write an XML file in Qt:

QString fname = "L.xml";
QFile file(fname);
if (file.open(QIODevice::WriteOnly)) {

    QTextStream streamFileOut(&file);
    streamFileOut.setCodec("Windows-1251");

    QString string;

    QXmlStreamWriter xmlWriter(&string);
    xmlWriter.setAutoFormatting(true);
    xmlWriter.writeStartDocument();
        xmlWriter.writeStartElement("LIST");

            xmlWriter.writeStartElement("V");
            xmlWriter.writeCharacters("Привет");
            xmlWriter.writeEndElement();

            xmlWriter.writeStartElement("S");
            xmlWriter.writeCharacters("Привет");
            xmlWriter.writeEndElement();


        xmlWriter.writeEndElement();
    xmlWriter.writeEndDocument();

    streamFileOut << string;
    streamFileOut.flush();
    file.close();
}

I get the following XML:

<?xml version="1.0"?>
<LIST>
    <V>Привет</V>
    <S>Привет</S>
</LIST>

I need to get the XML:

<?xml version="1.0" encoding="windows-1251" ?>
<LIST>
    <V>Привет</V>
    <S>Привет</S>
</LIST>

In my XML there is no encoding = "windows-1251". How to fix this?

Upvotes: 4

Views: 1214

Answers (1)

metal
metal

Reputation: 6332

Use QXmlStreamWriter::setCodec(), but you can't stream to a QString and still keep the encoding attribute, as the docs note. Going directly to a file, it works:

#include <QFile>
#include <QXmlStreamWriter>
#include <QString>

int main()
{
    auto file = QFile{ "L.xml" };
    if (file.open(QIODevice::WriteOnly))
    {
        auto xmlWriter = QXmlStreamWriter{ &file };
        xmlWriter.setAutoFormatting(true);
        xmlWriter.setCodec("windows-1251");
        xmlWriter.writeStartDocument();
        {
            xmlWriter.writeStartElement("LIST");
            {
                xmlWriter.writeStartElement("V");
                {
                    xmlWriter.writeCharacters(u8"Привет");
                }
                xmlWriter.writeEndElement();

                xmlWriter.writeStartElement("S");
                {
                    xmlWriter.writeCharacters(u8"Привет");
                }
                xmlWriter.writeEndElement();
            }
            xmlWriter.writeEndElement();
        }
        xmlWriter.writeEndDocument();
    }
}

Yields:

<?xml version="1.0" encoding="windows-1251"?>
<LIST>
    <V>Привет</V>
    <S>Привет</S>
</LIST>

Upvotes: 4

Related Questions