一 环境部署
QT的配置文件中添加xml选项:
二 写入xml文件
头文件:#include <QXmlStreamWriter>
bool MyXML::writeToXMLFile()
{QString currentTime = QDateTime::currentDateTime().toString("yyyyMMddhhmmss");QString fileName = "./testWrite.xml";QFile file(fileName);//QIODevice::Truncate 以重写的方式打开,在写入新的数据时会将原有数据全部清除if(!file.open(QIODevice::WriteOnly | QIODevice::Text |QIODevice::Truncate)){qDebug()<<"open xml file failed!";return false;}QXmlStreamWriter write(&file);//设置自动格式化,包括自动换行缩进等write.setAutoFormatting(true);write.writeStartDocument("1.0");//写入常规信息write.writeStartElement("Somebody info");write.writeTextElement("name","abby");write.writeTextElement("age",QString::number(18));write.writeTextElement("sex","女");//写入数组for(int i = 0; i < 2; i++){write.writeStartElement("hobby");write.writeAttribute("No",QString::number(i));write.writeTextElement("name",QString("piano").append(QString::number(i)));write.writeEndElement();}write.writeEndElement();write.writeEndDocument();file.close();return true;
}
写入的文件如图:
三 解析xml文件
头文件:#include <QXmlStreamReader>