Qt操作xml文件(增删改功能)

这个例子是在根据网上博客《Qt数据库(XML)》改写的一个操作XML的实现。

借鉴了很多里面的代码,大家可以结合上面的博客对照,相信你肯定会对XML的操作熟练起来。

我建立的是Qwidget项目,没有添加ui文件,输出内容都放在应用程序输出中(qDebug)。

XMLtest.pro文件代码:

  1. #-------------------------------------------------  
  2. #  
  3. # Project created by QtCreator 2012-08-15T15:56:54  
  4. #  
  5. #-------------------------------------------------  
  6.   
  7. QT       += core gui xml  
  8.   
  9. TARGET = XMLtest  
  10. TEMPLATE = app  
  11.   
  12.   
  13. SOURCES += main.cpp  
  14.         widget.cpp  
  15.   
  16. HEADERS  += widget.h  


widget.h文件代码:

  1. #ifndef WIDGET_H  
  2. #define WIDGET_H  
  3.   
  4. #include <QtGui/QWidget>  
  5. #include <QtCore>  
  6.   
  7.   
  8. class Widget : public QWidget  
  9. {  
  10.     Q_OBJECT  
  11.       
  12. public:  
  13.     Widget(QWidget *parent = 0);  
  14.     ~Widget();  
  15.   
  16.     void read_xml(QString filename);  
  17.     void create_xml(QString filename);  
  18.     void add_xmlnode(QString filename,QString rmt_name,QString ipa,QString ipb);  
  19.     void do_xml(const QString opt,QString filename);  
  20. private:  
  21. };  
  22.   
  23. #endif // WIDGET_H  


widget.cpp文件代码:

  1. #include "widget.h"  
  2. #include "qfile.h"  
  3. #include "qdebug.h"  
  4. #include <QDomDocument>  
  5. #include "qtextcodec.h"  
  6.   
  7. Widget::Widget(QWidget *parent)  
  8.     : QWidget(parent)  
  9. {  
  10.     QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GB2312"));  
  11.   
  12.     QFile *file;  
  13.     QString  filename = "config.xml";  
  14.     if(file->exists("config.xml"))  
  15.     {  
  16.         read_xml(filename);  
  17.     }  
  18.     else  
  19.     {  
  20.         create_xml(filename);  
  21.     }  
  22.   
  23.     add_xmlnode(filename,"remote1","127.0.0.1","192.168.1.199");  
  24.     do_xml("update",filename);  
  25. }  
  26.   
  27. Widget::~Widget()  
  28. {  
  29.       
  30. }  
  31.   
  32. void Widget::do_xml(const QString opt,QString filename)  
  33. {  
  34.     QFile file(filename);  
  35.     if(!file.open(QIODevice::ReadOnly | QIODevice::Text))  
  36.     {  
  37.         qDebug() << "open for do erro";  
  38.         file.close();  
  39.     }  
  40.   
  41.     QDomDocument doc;  
  42.     if(!doc.setContent(&file))  
  43.      {  
  44.         qDebug() << "setcontent for do error";  
  45.         file.close();  
  46.     }  
  47.     file.close();  
  48.     QDomNodeList lists = doc.elementsByTagName("remote");  
  49.     QDomElement ele = lists.at(1).toElement();  
  50.     if(ele.attribute(tr("id")) == "3")  
  51.     {  
  52.         if("delete" == opt || "update" == opt)  
  53.         {  
  54.             QDomElement root = doc.documentElement();  
  55.             if("delete" == opt)  
  56.             {  
  57.                 root.removeChild(lists.at(1));  
  58.                 qDebug() << "remove ok !";  
  59.             }  
  60.             else  
  61.             {  
  62.                 QDomNodeList child=lists.at(1).childNodes();  
  63.                 child.at(0).toElement().firstChild().setNodeValue("namechanged");  
  64.                 child.at(1).toElement().firstChild().setNodeValue("ipachanged");  
  65.                 child.at(2).toElement().firstChild().setNodeValue("ipbchanged");  
  66.                 qDebug() << "modify ok !";  
  67.             }  
  68.             if(!file.open(QIODevice::WriteOnly | QIODevice::Text))  
  69.             {  
  70.                 qDebug() << "open for remove error!";  
  71.             }  
  72.             QTextStream out(&file);  
  73.             doc.save(out,4);  
  74.             file.close();  
  75.   
  76.         }  
  77.     }  
  78. }  
  79.   
  80. void Widget::add_xmlnode(QString filename,QString rmt_name, QString ipa, QString ipb)  
  81. {  
  82.     QFile file(filename);  
  83.     if (!file.open(QIODevice::ReadOnly | QFile::Text)) {  
  84.         qDebug()<<"open for add error..." ;  
  85.     }  
  86.     QDomDocument doc;  
  87.     QString errorStr;  
  88.     int errorLine;  
  89.     int errorColumn;  
  90.   
  91.     if (!doc.setContent(&file, false, &errorStr, &errorLine, &errorColumn)) {  
  92.         qDebug()<<"add setcontent error..." ;  
  93.         file.close();  
  94.     }  
  95.     //QDomNode node = doc.firstChild();  
  96.     file.close();  
  97.     QDomElement root = doc.documentElement();  
  98.     if(root.isNull())  
  99.     {  
  100.         root = doc.createElement("ipconfig");  
  101.     }  
  102.     QDomElement element_root = doc.createElement(tr("remote"));  
  103.     QDomAttr attr_id = doc.createAttribute(tr("id"));  
  104.     QDomElement element_rmt = doc.createElement(tr("rmt_name"));  
  105.     QDomElement element_ipa = doc.createElement(tr("ipa"));  
  106.     QDomElement element_ipb = doc.createElement(tr("ipb"));  
  107.     QString str_id;  
  108.     if(root.lastChild().isNull())  
  109.     {  
  110.         str_id = "1";  
  111.         attr_id.setValue(str_id);  
  112.     }  
  113.     else  
  114.     {  
  115.         str_id = root.lastChild().toElement().attribute(tr("id"));  
  116.         int count = str_id.toInt()+1;  
  117.         attr_id.setValue(QString::number(count));  
  118.     }  
  119.     QDomText text;  
  120.     text =doc.createTextNode(rmt_name);  
  121.     element_rmt.appendChild(text);  
  122.     text = doc.createTextNode(ipa);  
  123.     element_ipa.appendChild(text);  
  124.     text = doc.createTextNode(ipb);  
  125.     element_ipb.appendChild(text);  
  126.     text.clear();  
  127.     element_root.appendChild(element_rmt);  
  128.     element_root.appendChild(element_ipa);  
  129.     element_root.appendChild(element_ipb);  
  130.     element_root.setAttributeNode(attr_id);  
  131.     root.appendChild(element_root);  
  132.   
  133.     if(!file.open(QIODevice::WriteOnly|QIODevice::Append))  
  134.         qDebug() << "open for add error!";  
  135.     QTextStream out(&file);  
  136.     doc.save(out,4);  
  137.     file.close();  
  138. }  
  139.   
  140. void Widget::read_xml(QString filename)  
  141. {  
  142.     QFile file(filename);  
  143.     if (!file.open(QIODevice::ReadOnly | QFile::Text)) {  
  144.         qDebug()<<"open for read error..." ;  
  145.     }  
  146.     QString errorStr;  
  147.     int errorLine;  
  148.     int errorColumn;  
  149.   
  150.     QDomDocument doc;  
  151.     if (!doc.setContent(&file, false, &errorStr, &errorLine, &errorColumn)) {  
  152.         qDebug()<<"setcontent error..." ;  
  153.         file.close();  
  154.     }  
  155.     file.close();  
  156.     QDomElement root = doc.documentElement();  
  157.     if (root.tagName() != "ipconfig") {  
  158.        qDebug()<<"root.tagname != ipconfig..." ;  
  159.     }  
  160.     QDomNode node = root.firstChild();  
  161.     while(!node.isNull())  
  162.     {  
  163.         if(node.isElement())  
  164.         {  
  165.             QDomElement element = node.toElement();  
  166.             qDebug() << qPrintable(element.tagName())<<qPrintable(element.attribute("id"));  
  167.             QDomNodeList list = element.childNodes();  
  168.             for(int i = 0;i < list.count();i++)  
  169.             {  
  170.                 QDomNode nodechild = list.at(i);  
  171.                 if(nodechild.isElement())  
  172.                 {  
  173.                     qDebug() << "    " << qPrintable(nodechild.toElement().tagName()) << qPrintable(nodechild.toElement().text());  
  174.                 }  
  175.             }  
  176.         }  
  177.         node = node.nextSibling();  
  178.     }  
  179. }  
  180.   
  181. void Widget::create_xml(QString filename)  
  182. {  
  183.     QFile file(filename);  
  184.     file.open(QIODevice::ReadWrite);  
  185.     QDomDocument doc;  
  186.     QDomProcessingInstruction instruction;  
  187.     instruction = doc.createProcessingInstruction("xml","version="1.0" encoding="GB2312"");  
  188.     doc.appendChild(instruction);  
  189.     QDomElement root = doc.createElement("ipconfig");  
  190.   
  191.     doc.appendChild(root);  
  192.     QDomText text = doc.createTextNode("");  
  193.     root.appendChild(text);  
  194.     QTextStream out(&file);  
  195.     doc.save(out,4);  
  196.     file.close();  
  197. }  


main.cpp文件代码:

  1. #include <QtGui/QApplication>  
  2. #include "widget.h"  
  3.   
  4. int main(int argc, char *argv[])  
  5. {  
  6.     QApplication a(argc, argv);  
  7.     Widget w;  
  8.     w.show();  
  9.       
  10.     return a.exec();  
  11. }  

XML文件结构:

  1. <?xml version='1.0' encoding='GB2312'?>  
  2. <ipconfig>  
  3.     <remote id="1">  
  4.         <rmt_name>remote1</rmt_name>  
  5.         <ipa>127.0.0.1</ipa>  
  6.         <ipb>192.168.1.199</ipb>  
  7.     </remote>  
  8.     <remote id="3">  
  9.         <rmt_name>namechanged</rmt_name>  
  10.         <ipa>ipachanged</ipa>  
  11.         <ipb>ipbchanged</ipb>  
  12.     </remote>  
  13.     <remote id="4">  
  14.         <rmt_name>remote1</rmt_name>  
  15.         <ipa>127.0.0.1</ipa>  
  16.         <ipb>192.168.1.199</ipb>  
  17.     </remote>  
  18.     <remote id="5">  
  19.         <rmt_name>remote1</rmt_name>  
  20.         <ipa>127.0.0.1</ipa>  
  21.         <ipb>192.168.1.199</ipb>  
  22.     </remote>  
  23.     <remote id="6">  
  24.         <rmt_name>remote1</rmt_name>  
  25.         <ipa>127.0.0.1</ipa>  
  26.         <ipb>192.168.1.199</ipb>  
  27.     </remote>  
  28.     <remote id="7">  
  29.         <rmt_name>remote1</rmt_name>  
  30.         <ipa>127.0.0.1</ipa>  
  31.         <ipb>192.168.1.199</ipb>  
  32.     </remote>  
  33.     <remote id="8">  
  34.         <rmt_name>remote1</rmt_name>  
  35.         <ipa>127.0.0.1</ipa>  
  36.         <ipb>192.168.1.199</ipb>  
  37.     </remote>  
  38. </ipconfig>  


 

应用程序输出:

remote 1

rmt_name remote1

ipa 127.0.0.1

ipb 192.168.1.199

remote 3

rmt_name remote1

ipa 127.0.0.1

ipb 192.168.1.199

remote 4

rmt_name remote1

ipa 127.0.0.1

ipb 192.168.1.199

remote 5

rmt_name remote1

ipa 127.0.0.1

ipb 192.168.1.199

remote 6

rmt_name remote1

ipa 127.0.0.1

ipb 192.168.1.199

remote 7

rmt_name remote1

ipa 127.0.0.1

ipb 192.168.1.199

modify ok !

原文地址:https://www.cnblogs.com/cy568searchx/p/3628601.html