转自QT4.86写中文XML
新建Qt空项目名称xml.pro
xml.pro
QT += core gui xml
SOURCES += \
main.cpp
main.cpp
#include <QtGui/QApplication>
#include <QTextCodec>
#include <QFile>
#include <QXmlStreamWriter>
int main()
{
//QTextCodec::setCodecForCStrings(QTextCodec::codecForName("gb18030"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf-8"));
QFile file("test.xml");
if(! file.open(QIODevice::ReadWrite))
return 0;
QXmlStreamWriter writer(&file);
writer.setAutoFormatting(true);
// 作用类似于创建一个xml文档,并在文档开头部分写入版本信息和编码信息。
writer.writeStartDocument();//生成的文件开头标识仍是utf-8
//writer.setCodec("gb18030");
writer.setCodec("UTF-8");
writer.writeStartElement("Start");
writer.writeAttribute("animinal","cat");
writer.writeTextElement("book","book1");
writer.writeTextElement("book","中国");
writer.writeEndElement();//Start
writer.writeEndDocument();
file.close();
return 0;
}