QT DOM方式写入xml文件

来源:互联网 发布:破解版360企业云盘mac 编辑:程序博客网 时间:2024/06/07 22:30


依赖的头文件:

[cpp] view plaincopyprint?
  1. #include <QFile>   
  2. #include <QString>  
  3. #include <QtXml>  
  4. #include <QDomDocument>  
  5. #include <QDateTime>  

示例代码:


[cpp] view plaincopyprint?
  1. //写xml操作。sXmlFilePath:要写入的xml文件路径  
  2. int CAppletGenerator::addTaskMenuTreeItem(QString sXmlFilePath)  
  3. {  
  4.     QFile file(sXmlFilePath);  
  5.     if (!file.open(QFile::ReadOnly | QFile::Text)) {  
  6.         return -1;  
  7.     }  
  8.   
  9.     QDomDocument domDocument;  
  10.     if (!domDocument.setContent(&file, true)) {  
  11.         file.close();  
  12.         return -1;  
  13.     }  
  14.     QDomElement tree      = domDocument.documentElement();  
  15.     QDomElement firstItem = tree.firstChildElement();  
  16.   
  17.     //在firstitem上添加一个节点  
  18.     QDomElement secondItem = domDocument.createElement("item");  
  19.   
  20.     //获取当前时间,用于节点的唯一性id  
  21.     QDateTime dt;  
  22.     QTime time;  
  23.     QDate date;  
  24.     dt.setTime(time.currentTime());  
  25.     dt.setDate(date.currentDate());  
  26.     QString currentDate = dt.toString("yyyyMMddhhmmss");  
  27.   
  28.     //为节点添加属性  
  29.     secondItem.setAttribute("id",currentDate);  
  30.     secondItem.setAttribute("select","1");  
  31.     secondItem.setAttribute("text","节点");  
  32.   
  33.     //添加元素节点到父节点  
  34.     firstItem.appendChild(secondItem);  
  35.     file.close();  
  36.   
  37.     QFile fileModify(sXmlFilePath);  
  38.     if (!fileModify.open(QFile::WriteOnly | QFile::Text)){  
  39.         return -1;  
  40.     }  
  41.   
  42.     //核心代码:Dom方式写xml文件  
  43.     QTextStream out(&fileModify);  
  44.     domDocument.save(out,4);  
  45.     fileModify.close();  
  46.     return 0;  
  47.   
  48. }  

原文地址:http://blog.csdn.net/ymc0329/article/details/6709223

0 0
原创粉丝点击