在Qt中,我们有时候需要把一些参数写入xml文件,方便以后可以读入,类似一种存档读档的操作,例如,我们想生成如下的xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<Parameters>
<para1>1</para1>
<para2>2</para2>
<para3>3</para3>
</Parameters>

那么写入的操作请参见如下代码:

void QtMainWindow::on_actionSave_triggered() {
QString filename = QFileDialog::getSaveFileName(this,
tr("Save Xml"), ".",
tr("Xml files (*.xml)"));
QFile file(filename);
file.open(QIODevice::WriteOnly);
QXmlStreamWriter xmlWriter(&file);
xmlWriter.setAutoFormatting(true);
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement("Parameters");
xmlWriter.writeTextElement("para1",QString::number());
xmlWriter.writeTextElement("para2",QString::number());
xmlWriter.writeTextElement("para3",QString::number());
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
file.close();
}

读入的操作请参见如下:

void QtMainWindow::on_actionLoad_triggered() {
QString filename = QFileDialog::getOpenFileName(this,
tr("Open Xml"), ".",
tr("Xml files (*.xml)"));
QFile file(filename);
if (!file.open(QFile::ReadOnly | QFile::Text)) {
std::cerr << "Error: Cannot read file " << qPrintable(filename)
<< ": " << qPrintable(file.errorString())
<< std::endl;
}
QXmlStreamReader xmlReader(&file);
xmlReader.readNext();
while(!xmlReader.atEnd()) {
if(xmlReader.isStartElement()) {
if(xmlReader.name() == "Parameters") {
xmlReader.readNext();
} else if (xmlReader.name() == "para1") {
int para1 = xmlReader.readElementText().toInt();
xmlReader.readNext();
} else if (xmlReader.name() == "preFilterCap") {
int para2 = xmlReader.readElementText().toInt();
xmlReader.readNext();
} else if (xmlReader.name() == "SADWindowSize") {
int para3 = xmlReader.readElementText().toInt();
xmlReader.readNext();
} else {
xmlReader.raiseError(QObject::tr("Not a options file"));
}
} else {
xmlReader.readNext();
}
file.close();
if (xmlReader.hasError()) {
std::cerr << "Error: Failed to parse file "
<< qPrintable(filename) << ": "
<< qPrintable(xmlReader.errorString()) << std::endl;
} else if (file.error() != QFile::NoError) {
std::cerr << "Error: Cannot read file " << qPrintable(filename)
<< ": " << qPrintable(file.errorString())
<< std::endl;
}
}
}
04-03 05:55