发现用 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 ! ", filename, file.errorString().toStdString().c_str() );
- return;
- }
- QDomDocument document;
- QString strError;
- int errLin = 0, errCol = 0;
- if( !document.setContent(&file, false, &strError, &errLin, &errCol) ) {
- printf( "parse file failed at line %d column %d, error: %s ! ", errLin, errCol, strError );
- return;
- }
- if( document.isNull() ) {
- printf( "document is null ! " );
- return;
- }
- QDomElement root = document.documentElement();
- printf( "%s ", root.tagName().toStdString().c_str() );
- if( root.hasAttribute("name") )
- printf( "%s ", root.attributeNode("name").value().toStdString().c_str() );
- QDomElement files = root.firstChildElement();
- if( files.isNull() )
- return;
- else
- printf( " %s ", files.tagName().toStdString().c_str() );
- QDomElement element = files.firstChildElement();
- while( !element.isNull() ) {
- if( element.hasAttribute("name") )
- printf( " file: %s", element.attributeNode("name").value().toStdString().c_str() );
- if( element.hasAttribute("size") )
- printf( " %s", element.attributeNode("size").value().toStdString().c_str() );
- printf( " " );
- 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 文件的生存还没有研究过,以后有时间再说。