Qt解析xml


發現用 Qt 解析 xml 文件非常方便,下面是一個簡單的解析 xml 文件的例子:

[cpp]  view plain copy
  1. #include <QtCore/QCoreApplication>  
  2. #include <QDomDocument>  
  3. #include <QDomElement>  
  4. #include <QDomAttr>  
  5. #include <QFile>  
  6.   
  7. void parse( const char *filename )  
  8. {  
  9.     if( NULL == filename )  
  10.         return;  
  11.   
  12.     QFile file( filename );  
  13.     if( !file.open(QFile::ReadOnly | QFile::Text) ) {  
  14.         printf( "open file '%s' failed, error: %s !\n", filename, file.errorString().toStdString().c_str() );  
  15.         return;  
  16.     }  
  17.   
  18.     QDomDocument    document;  
  19.     QString         strError;  
  20.     int             errLin = 0, errCol = 0;  
  21.     if( !document.setContent(&file, false, &strError, &errLin, &errCol) ) {  
  22.         printf( "parse file failed at line %d column %d, error: %s !\n", errLin, errCol, strError );  
  23.         return;  
  24.     }  
  25.   
  26.     if( document.isNull() ) {  
  27.         printf( "document is null !\n" );  
  28.         return;  
  29.     }  
  30.   
  31.     QDomElement root = document.documentElement();  
  32.     printf( "%s ", root.tagName().toStdString().c_str() );  
  33.     if( root.hasAttribute("name") )  
  34.         printf( "%s\n", root.attributeNode("name").value().toStdString().c_str() );  
  35.   
  36.     QDomElement files = root.firstChildElement();  
  37.     if( files.isNull() )  
  38.         return;  
  39.     else  
  40.         printf( "\t%s\n", files.tagName().toStdString().c_str() );  
  41.   
  42.     QDomElement element = files.firstChildElement();  
  43.     while( !element.isNull() ) {  
  44.         if( element.hasAttribute("name") )  
  45.             printf( "\t\t file: %s", element.attributeNode("name").value().toStdString().c_str() );  
  46.         if( element.hasAttribute("size") )  
  47.             printf( "\t %s", element.attributeNode("size").value().toStdString().c_str() );  
  48.         printf( "\n" );  
  49.         element = element.nextSiblingElement();  
  50.     }  
  51. }  
  52.   
  53. int main(int argc, char *argv[])  
  54. {  
  55.     QCoreApplication a(argc, argv);  
  56.   
  57.     char filename[256] = { 0 };  
  58.     printf( "please input file name: " );  
  59.     gets( filename );  
  60.   
  61.     parse( filename );  
  62.   
  63.     return a.exec();  
  64. }  


執行效果:

xml文件:

 

這個只是 xml 文件解析的例子,xml 文件的生存還沒有研究過,以后有時間再說。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM