zoukankan      html  css  js  c++  java
  • Qt解析xml

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

    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 ! ", 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 ! ", errLin, errCol, strError );  
    23.         return;  
    24.     }  
    25.   
    26.     if( document.isNull() ) {  
    27.         printf( "document is null ! " );  
    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 ", root.attributeNode("name").value().toStdString().c_str() );  
    35.   
    36.     QDomElement files = root.firstChildElement();  
    37.     if( files.isNull() )  
    38.         return;  
    39.     else  
    40.         printf( " %s ", files.tagName().toStdString().c_str() );  
    41.   
    42.     QDomElement element = files.firstChildElement();  
    43.     while( !element.isNull() ) {  
    44.         if( element.hasAttribute("name") )  
    45.             printf( "  file: %s", element.attributeNode("name").value().toStdString().c_str() );  
    46.         if( element.hasAttribute("size") )  
    47.             printf( "  %s", element.attributeNode("size").value().toStdString().c_str() );  
    48.         printf( " " );  
    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 文件的生存还没有研究过,以后有时间再说。

  • 相关阅读:
    .net 设置默认首页
    MySQL如何对数据库状态值指定排序
    golang将mm-dd-yy的字符串转时间格式
    Nginx文件解析
    Git使用笔记
    批量导入实现逻辑
    golang字符串截取
    golang格式化代码
    golang获取某一年某一月份的开始日期和结束日期
    nslookup install
  • 原文地址:https://www.cnblogs.com/cy568searchx/p/3628597.html
Copyright © 2011-2022 走看看