Qt读写XML文件
发布时间:2020-12-16 00:21:47 所属栏目:百科 来源:网络整理
导读:1 写XML : main.cpp #include QtCore#include QDebug#include QtXmlint main(int argc,char *argv[]){ QCoreApplication a(argc,argv); //Write XML QDomDocument document; //Make the root element QDomElement root =document.createElement("Books"); //
1 写XML : main.cpp #include <QtCore> #include <QDebug> #include <QtXml> int main(int argc,char *argv[]) { QCoreApplication a(argc,argv); //Write XML QDomDocument document; //Make the root element QDomElement root =document.createElement("Books"); //Add it to the documnet document.appendChild(root); //Add some elements for(int i =0;i<10;++i) { QDomElement book = document.createElement("Book"); book.setAttribute("Name","My Book " +QString::number(i)); book.setAttribute("ID",QString::number(i)); root.appendChild(book); for(int h=0;h<10;h++) { QDomElement chapter = document.createElement("Chapter"); chapter.setAttribute("Name","My Chapter " +QString::number(i)); chapter.setAttribute("ID",QString::number(i)); book.appendChild(chapter); } } QFile file("MyXml.xml"); if(!file.open(QIODevice::WriteOnly |QIODevice::Text)) { qDebug("Failed to open file for writting!"); return -1; } else { QTextStream stream(&file); stream<<document.toString(); file.close(); qDebug("Finished"); } return a.exec(); } 2 读XML:main.cpp #include <QtCore> #include <QtXml> #include <QDebug> int main(int argc,argv); QDomDocument document; //Load the file QFile file("MyXml.xml"); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug()<<"Failed to open file!"; return -1; } else { if(document.setContent(&file)) { qDebug("Failed to load document"); return -1; } file.close(); } QDomElement doc_elem = document.documentElement(); QDomNode n = doc_elem.firstChild(); while(!n.isNull()) { QDomElement elem = n.toElement(); // 将节点转换为元素 if(!elem.isNull()) { if(elem.attribute("name") == "iStonsoft Image Converter") { QString str = elem.attribute("version");// str 为 version对应的内容 } } n = n.nextSibling(); } return a.exec(); } 3 以上代码适合读取的XML文件类型 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |