QxmlStreamWrite
void MsgModel::save_messge()
{
QFile file("message.xml");
if(file.open(QIODevice::WriteOnly | QIODevice::Text))
{
QXmlStreamWriter writer(&file);
writer.setAutoFormatting(true);
writer.writeStartDocument();
writer.writeStartElement("DATA");
std::multimap<QString, Message*>::iterator pos;
for(pos = message_map->begin();pos != message_map->end();pos++)
{
Message *message = pos->second;
writer.writeStartElement("Sms");
writer.writeTextElement("Name", message->GetMsgName());
writer.writeTextElement("Number", message->GetMsgPhone());
writer.writeTextElement("Content", message->GetMsgContent());
writer.writeTextElement("Time", message->GetMsgTime());
writer.writeEndElement();
}
writer.writeEndElement();
writer.writeEndDocument();
file.close();
}
}
QxmlStreamRead
QXmlStreamReader reader;
QFile file(QApplication::applicationDirPath() + "/demo.xml");
if (!file.open(QFile::ReadOnly | QFile::Text))
{
QMessageBox::critical(this, tr("Error"),
tr("Cannot read file %1").arg(fileName));
return false;
}
reader.setDevice(&file);
while (!reader.atEnd())
{
if (reader.isStartElement())
{
qDebug()<<"2222222222222222";
if (reader.name() == "bookindex")
{
readBookindexElement();//递归下降算法,层层读取
}
else
{
reader.raiseError(tr("Not a valid book file"));
}
}
else
{
qDebug()<<"111111111111111";
reader.readNext(); //循坏调用首次移动3次,后面移动一次
}
}
file.close();
if (reader.hasError())
{
QMessageBox::critical(this, tr("Error"),
tr("Failed to parse file %1").arg(fileName));
return false;
}
else if (file.error() != QFile::NoError)
{
QMessageBox::critical(this, tr("Error"),
tr("Cannot read file %1").arg(fileName));
return false;
}
return true;
void MainWindow::readBookindexElement()
{
Q_ASSERT(reader.isStartElement() && reader.name() == "bookindex");//不是则会报错
reader.readNext(); // 读取下一个记号,它返回记号的类型
while (!reader.atEnd())
{
if (reader.isEndElement())
{
reader.readNext();
break;
}
if (reader.isStartElement())
{
if (reader.name() == "entry")
{
readEntryElement(treeWidget->invisibleRootItem());
}
else
{
skipUnknownElement();
}
}
else
{
reader.readNext();
}
}
}