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  
#-------------------------------------------------
#
# Project created by QtCreator 2012-08-15T15:56:54
#
#-------------------------------------------------

QT       += core gui xml

TARGET = XMLtest
TEMPLATE = app


SOURCES += main.cpp\
        widget.cpp

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  
#ifndef WIDGET_H
#define WIDGET_H

#include <QtGui/QWidget>
#include <QtCore>


class Widget : public QWidget
{
    Q_OBJECT
    
public:
    Widget(QWidget *parent = 0);
    ~Widget();

    void read_xml(QString filename);
    void create_xml(QString filename);
    void add_xmlnode(QString filename,QString rmt_name,QString ipa,QString ipb);
    void do_xml(const QString opt,QString filename);
private:
};

#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. }  
#include "widget.h"
#include "qfile.h"
#include "qdebug.h"
#include <QDomDocument>
#include "qtextcodec.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GB2312"));

    QFile *file;
    QString  filename = "config.xml";
    if(file->exists("config.xml"))
    {
        read_xml(filename);
    }
    else
    {
        create_xml(filename);
    }

    add_xmlnode(filename,"remote1","127.0.0.1","192.168.1.199");
    do_xml("update",filename);
}

Widget::~Widget()
{
    
}

void Widget::do_xml(const QString opt,QString filename)
{
    QFile file(filename);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "open for do erro";
        file.close();
    }

    QDomDocument doc;
    if(!doc.setContent(&file))
     {
        qDebug() << "setcontent for do error";
        file.close();
    }
    file.close();
    QDomNodeList lists = doc.elementsByTagName("remote");
    QDomElement ele = lists.at(1).toElement();
    if(ele.attribute(tr("id")) == "3")
    {
        if("delete" == opt || "update" == opt)
        {
            QDomElement root = doc.documentElement();
            if("delete" == opt)
            {
                root.removeChild(lists.at(1));
                qDebug() << "remove ok !";
            }
            else
            {
                QDomNodeList child=lists.at(1).childNodes();
                child.at(0).toElement().firstChild().setNodeValue("namechanged");
                child.at(1).toElement().firstChild().setNodeValue("ipachanged");
                child.at(2).toElement().firstChild().setNodeValue("ipbchanged");
                qDebug() << "modify ok !";
            }
            if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
            {
                qDebug() << "open for remove error!";
            }
            QTextStream out(&file);
            doc.save(out,4);
            file.close();

        }
    }
}

void Widget::add_xmlnode(QString filename,QString rmt_name, QString ipa, QString ipb)
{
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly | QFile::Text)) {
        qDebug()<<"open for add error..." ;
    }
    QDomDocument doc;
    QString errorStr;
    int errorLine;
    int errorColumn;

    if (!doc.setContent(&file, false, &errorStr, &errorLine, &errorColumn)) {
        qDebug()<<"add setcontent error..." ;
        file.close();
    }
    //QDomNode node = doc.firstChild();
    file.close();
    QDomElement root = doc.documentElement();
    if(root.isNull())
    {
        root = doc.createElement("ipconfig");
    }
    QDomElement element_root = doc.createElement(tr("remote"));
    QDomAttr attr_id = doc.createAttribute(tr("id"));
    QDomElement element_rmt = doc.createElement(tr("rmt_name"));
    QDomElement element_ipa = doc.createElement(tr("ipa"));
    QDomElement element_ipb = doc.createElement(tr("ipb"));
    QString str_id;
    if(root.lastChild().isNull())
    {
        str_id = "1";
        attr_id.setValue(str_id);
    }
    else
    {
        str_id = root.lastChild().toElement().attribute(tr("id"));
        int count = str_id.toInt()+1;
        attr_id.setValue(QString::number(count));
    }
    QDomText text;
    text =doc.createTextNode(rmt_name);
    element_rmt.appendChild(text);
    text = doc.createTextNode(ipa);
    element_ipa.appendChild(text);
    text = doc.createTextNode(ipb);
    element_ipb.appendChild(text);
    text.clear();
    element_root.appendChild(element_rmt);
    element_root.appendChild(element_ipa);
    element_root.appendChild(element_ipb);
    element_root.setAttributeNode(attr_id);
    root.appendChild(element_root);

    if(!file.open(QIODevice::WriteOnly|QIODevice::Append))
        qDebug() << "open for add error!";
    QTextStream out(&file);
    doc.save(out,4);
    file.close();
}

void Widget::read_xml(QString filename)
{
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly | QFile::Text)) {
        qDebug()<<"open for read error..." ;
    }
    QString errorStr;
    int errorLine;
    int errorColumn;

    QDomDocument doc;
    if (!doc.setContent(&file, false, &errorStr, &errorLine, &errorColumn)) {
        qDebug()<<"setcontent error..." ;
        file.close();
    }
    file.close();
    QDomElement root = doc.documentElement();
    if (root.tagName() != "ipconfig") {
       qDebug()<<"root.tagname != ipconfig..." ;
    }
    QDomNode node = root.firstChild();
    while(!node.isNull())
    {
        if(node.isElement())
        {
            QDomElement element = node.toElement();
            qDebug() << qPrintable(element.tagName())<<qPrintable(element.attribute("id"));
            QDomNodeList list = element.childNodes();
            for(int i = 0;i < list.count();i++)
            {
                QDomNode nodechild = list.at(i);
                if(nodechild.isElement())
                {
                    qDebug() << "    " << qPrintable(nodechild.toElement().tagName()) << qPrintable(nodechild.toElement().text());
                }
            }
        }
        node = node.nextSibling();
    }
}

void Widget::create_xml(QString filename)
{
    QFile file(filename);
    file.open(QIODevice::ReadWrite);
    QDomDocument doc;
    QDomProcessingInstruction instruction;
    instruction = doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"GB2312\"");
    doc.appendChild(instruction);
    QDomElement root = doc.createElement("ipconfig");

    doc.appendChild(root);
    QDomText text = doc.createTextNode("");
    root.appendChild(text);
    QTextStream out(&file);
    doc.save(out,4);
    file.close();
}


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. }  
#include <QtGui/QApplication>
#include "widget.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    
    return a.exec();
}

 

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>  
<?xml version='1.0' encoding='GB2312'?>
<ipconfig>
    <remote id="1">
        <rmt_name>remote1</rmt_name>
        <ipa>127.0.0.1</ipa>
        <ipb>192.168.1.199</ipb>
    </remote>
    <remote id="3">
        <rmt_name>namechanged</rmt_name>
        <ipa>ipachanged</ipa>
        <ipb>ipbchanged</ipb>
    </remote>
    <remote id="4">
        <rmt_name>remote1</rmt_name>
        <ipa>127.0.0.1</ipa>
        <ipb>192.168.1.199</ipb>
    </remote>
    <remote id="5">
        <rmt_name>remote1</rmt_name>
        <ipa>127.0.0.1</ipa>
        <ipb>192.168.1.199</ipb>
    </remote>
    <remote id="6">
        <rmt_name>remote1</rmt_name>
        <ipa>127.0.0.1</ipa>
        <ipb>192.168.1.199</ipb>
    </remote>
    <remote id="7">
        <rmt_name>remote1</rmt_name>
        <ipa>127.0.0.1</ipa>
        <ipb>192.168.1.199</ipb>
    </remote>
    <remote id="8">
        <rmt_name>remote1</rmt_name>
        <ipa>127.0.0.1</ipa>
        <ipb>192.168.1.199</ipb>
    </remote>
</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 !



http://blog.csdn.net/envenler/article/details/7874435
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值