Qt解析xml

来源:互联网 发布:淘宝买家评论怎么写 编辑:程序博客网 时间:2024/05/19 17:25

         发现用 Qt 解析 xml 文件非常方便,下面是一个简单的解析 xml 文件的例子:

#include <QtCore/QCoreApplication>#include <QDomDocument>#include <QDomElement>#include <QDomAttr>#include <QFile>void parse( const char *filename ){if( NULL == filename )return;QFile file( filename );if( !file.open(QFile::ReadOnly | QFile::Text) ) {printf( "open file '%s' failed, error: %s !\n", filename, file.errorString().toStdString().c_str() );return;}QDomDocumentdocument;QStringstrError;interrLin = 0, errCol = 0;if( !document.setContent(&file, false, &strError, &errLin, &errCol) ) {printf( "parse file failed at line %d column %d, error: %s !\n", errLin, errCol, strError );return;}if( document.isNull() ) {printf( "document is null !\n" );return;}QDomElement root = document.documentElement();printf( "%s ", root.tagName().toStdString().c_str() );if( root.hasAttribute("name") )printf( "%s\n", root.attributeNode("name").value().toStdString().c_str() );QDomElement files = root.firstChildElement();if( files.isNull() )return;elseprintf( "\t%s\n", files.tagName().toStdString().c_str() );QDomElement element = files.firstChildElement();while( !element.isNull() ) {if( element.hasAttribute("name") )printf( "\t\t file: %s", element.attributeNode("name").value().toStdString().c_str() );if( element.hasAttribute("size") )printf( "\t %s", element.attributeNode("size").value().toStdString().c_str() );printf( "\n" );element = element.nextSiblingElement();}}int main(int argc, char *argv[]){QCoreApplication a(argc, argv);char filename[256] = { 0 };printf( "please input file name: " );gets( filename );parse( filename );return a.exec();}


执行效果:

xml文件:

 

这个只是 xml 文件解析的例子,xml 文件的生存还没有研究过,以后有时间再说。

原创粉丝点击