gpt4 book ai didi

c++ - 如何在Qt中设置XML文件的编码?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:49:52 24 4
gpt4 key购买 nike

我用 Qt 写了一个 XML 文件:

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();
}

我得到以下 XML:

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

我需要获取 XML:

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

在我的 XML 中没有encoding = "windows-1251"。如何解决这个问题?

最佳答案

使用QXmlStreamWriter::setCodec() ,但您不能流式传输到 QString 并仍然保留编码属性,如文档所述。直接转到一个文件,它有效:

#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();
}
}

产量:

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

关于c++ - 如何在Qt中设置XML文件的编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55162811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com