一 环境部署
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("SomebodyInfo");
write.writeTextElement("name","abby");
write.writeTextElement("age",QString::number(18));
write.writeTextElement("sex","girl");
//写入数组
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>
bool MyXML::parseXMLFile()
{
QString fileName = "./testWrite.xml";
QFile file(fileName);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
qDebug()<<"open xml file failed!";
return false;
}
QXmlStreamReader reader(&file);
//过滤首行
reader.readNext();
while(!reader.atEnd()){
reader.readNext();
if(reader.isStartElement()){
if(reader.name() == "name"){
qDebug()<<"name = "<<reader.readElementText();
}
else if(reader.name() == "age"){
qDebug()<<"age = "<<reader.readElementText();
}
else if(reader.name() == "sex"){
qDebug()<<"sex = "<<reader.readElementText();
}
else if(reader.name() == "hobby"){
parseHobby(reader);
}
}
else if(reader.isEndElement()){
break;
}
}
}
解析其中的Hobby模块:
bool MyXML::parseHobby(QXmlStreamReader &reader)
{
QVector<QString> hobbyVec;
QString hobby;
while(!reader.atEnd()){
reader.readNext();
if(reader.isStartElement()){
if(reader.name() == "name"){
hobby = reader.readElementText();
hobbyVec.push_back(hobby);
}
}
else if(reader.isEndElement()){
for(int i = 0; i < hobbyVec.size();i++){
qDebug()<<"hobby i= "<<QString::number(i)<<"name = "<<hobbyVec[i];
}
break;
}
}
}
输出结果: