QT开发之XML(DOM接口)

XML是类似HTML的WEB前端标识符语言,这个比较简单,大家可以去学习一下,HTML+CSS+JS可以做一个非常不错的网站,我个人网站就是用这个框架开发的,也可以用JSP或PHP去开发,这里我们的重点是QT.这个下面我直接上代码就行,相信大家能够看懂.

QT提供了三种解析方法:SAX(Simple API XML), DOM(Document Object Model), Pull.   这篇文章我讲解DOM接口方法.

我们新建Qt  GUI应用项目,名称为myDOM.在myDOM.pro中添加QT += xml.导入QtXml模块.


mian.cpp

#include <QtGui/QApplication>
#include "mainwindow.h"
#include <QTextCodec>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
    MainWindow w;
    w.show();
    
    return a.exec();
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
    class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void doXml(const QString operate);

private slots:
    void on_pushButton_5_clicked();

    void on_pushButton_4_clicked();

    void on_pushButton_clicked();

    void on_pushButton_2_clicked();

    void on_pushButton_3_clicked();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtXml>
#include <QFile>

/* 在构造函数创建了一个xml格式的文件保存在my.xml文件中 */
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QDomDocument doc;

    QDomProcessingInstruction instruction;
    instruction = doc.createProcessingInstruction("xml",
                                                  "version=\"1.0\" encoding=\"UTF-8\"");
    doc.appendChild(instruction);

    QDomElement root = doc.createElement(QString("书库"));
    doc.appendChild(root);

    QDomElement book = doc.createElement(QString("图书"));
    QDomAttr id = doc.createAttribute(QString("编号"));
    QDomElement title = doc.createElement(QString("书名"));
    QDomElement author = doc.createElement(QString("作者"));
    QDomText text;

    id.setValue(QString("1"));
    book.setAttributeNode(id);
    text = doc.createTextNode(QString("Qt"));
    title.appendChild(text);
    text = doc.createTextNode(QString("shiming"));
    author.appendChild(text);
    book.appendChild(title);
    book.appendChild(author);
    root.appendChild(book);

    book = doc.createElement(QString("图书"));
    id = doc.createAttribute(QString("编号"));
    title = doc.createElement(QString("书名"));
    author = doc.createElement(QString("作者"));

    id.setValue(QString("2"));
    book.setAttributeNode(id);
    text = doc.createTextNode(QString("Linux"));
    title.appendChild(text);
    text = doc.createTextNode(QString("Linux_Google"));
    author.appendChild(text);
    book.appendChild(title);
    book.appendChild(author);
    root.appendChild(book);

    QFile file("my.xml");
    if(!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) return ;
    QTextStream out(&file);

    doc.save(out, 4);  /* 保存文件,4为子元素的缩进字符数 */
    file.close();
}

MainWindow::~MainWindow()
{
    delete ui;
}

/* 显示xml文件内容到listWidget文本框中 */
void MainWindow::on_pushButton_5_clicked()
{
    ui->listWidget->clear();
    QFile file("my.xml");
    if (!file.open(QIODevice::ReadOnly)) return ;
    QDomDocument doc;
    if (!doc.setContent(&file))
    {
        file.close();
        return ;
    }
    file.close();

    QDomElement docElem = doc.documentElement();

    QDomNode n = docElem.firstChild();
    while(!n.isNull())
    {
        if (n.isElement())
        {
            QDomElement e = n.toElement();
            ui->listWidget->addItem(e.tagName() + e.attribute(QString("编号")));
            QDomNodeList list = e.childNodes();
            for(int i=0; i<list.count(); i++)
            {
                QDomNode node = list.at(i);
                if(node.isElement())
                    ui->listWidget->addItem("   " + node.toElement().tagName()
                                            + " : " + node.toElement().text());
            }
        }
        n = n.nextSibling();
    }
}

/* 添加作者和名字到xml文件中 */
void MainWindow::on_pushButton_4_clicked()
{
    ui->listWidget->clear();
    ui->listWidget->addItem(QString("无法添加"));
    QFile file("my.xml");
    if (!file.open(QIODevice::ReadOnly)) return;
    QDomDocument doc;
    if (!doc.setContent(&file))
    {
        file.close();
        return;
    }
    file.close();
    QDomElement root = doc.documentElement();

    QDomElement book = doc.createElement(QString("图书"));
    QDomAttr id = doc.createAttribute(QString("编号"));
    QDomElement title = doc.createElement(QString("书名"));
    QDomElement author = doc.createElement(QString("作者"));
    QDomText text;

    QString num = root.lastChild().toElement().attribute(QString("编号"));
    int count = num.toInt() +1;
    id.setValue(QString::number(count));

    book.setAttributeNode(id);
    text = doc.createTextNode(ui->lineEdit_2->text());
    title.appendChild(text);
    text = doc.createTextNode(ui->lineEdit_3->text());
    author.appendChild(text);
    book.appendChild(title);
    book.appendChild(author);
    root.appendChild(book);

    if(!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) return ;
    QTextStream out(&file);
    doc.save(out, 4);   /* 保存到文件中 */
    file.close();

    ui->listWidget->clear();
    ui->listWidget->addItem(QString("添加成功!"));
}

void MainWindow::doXml(const QString operate)
{
    ui->listWidget->clear();
    ui->listWidget->addItem(QString("没有找到相关内容!"));
    QFile file("my.xml");
    if (!file.open(QIODevice::ReadOnly)) return ;
    QDomDocument doc;
    if (!doc.setContent(&file))
    {
        file.close();
        return ;
    }
    file.close();

    QDomNodeList list = doc.elementsByTagName(QString("图书"));

    for(int i=0; i<list.count(); i++)
    {
        QDomElement e = list.at(i).toElement();
        if(e.attribute(QString("编号")) == ui->lineEdit->text())
        {
            if(operate == "delete")
            {
                QDomElement root = doc.documentElement();

                root.removeChild(list.at(i));
                QFile file("my.xml");
                if(!file.open(QIODevice::WriteOnly | QIODevice::Truncate))
                    return ;
                QTextStream out(&file);
                doc.save(out,4);
                file.close();
                ui->listWidget->clear();
                ui->listWidget->addItem(QString("删除成功!"));
            }
            else if(operate == "update")
            {
                QDomNodeList child = list.at(i).childNodes();

                child.at(0).toElement().firstChild()
                        .setNodeValue(ui->lineEdit_2->text());
                child.at(1).toElement().firstChild()
                        .setNodeValue(ui->lineEdit_3->text());
                QFile file("my.xml");
                if(!file.open(QIODevice::WriteOnly | QIODevice::Truncate))
                    return ;
                QTextStream out(&file);
                doc.save(out,4);
                file.close();
                ui->listWidget->clear();
                ui->listWidget->addItem(QString("更新成功"));
            }
            else if(operate == "find")
            {

                ui->listWidget->clear();
                ui->listWidget->addItem(e.tagName()
                                        + e.attribute(QString("编号")));
                QDomNodeList list = e.childNodes();
                for(int i=0; i<list.count(); i++)
                {
                    QDomNode node = list.at(i);
                    if(node.isElement())
                        ui->listWidget->addItem("   "
                                                + node.toElement().tagName() + " : "
                                                + node.toElement().text());
                }
            }
        }
    }
}

void MainWindow::on_pushButton_clicked()
{
    doXml("find");
}


void MainWindow::on_pushButton_2_clicked()
{
    doXml("delete");
}


void MainWindow::on_pushButton_3_clicked()
{
    doXml("update");
}

mainwindow.ui设计界面和代码如下:


<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralWidget">
   <widget class="QListWidget" name="listWidget">
    <property name="geometry">
     <rect>
      <x>195</x>
      <y>1</y>
      <width>201</width>
      <height>171</height>
     </rect>
    </property>
   </widget>
   <widget class="QLabel" name="label">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>20</y>
      <width>61</width>
      <height>16</height>
     </rect>
    </property>
    <property name="text">
     <string>图书编号:</string>
    </property>
   </widget>
   <widget class="QLineEdit" name="lineEdit">
    <property name="geometry">
     <rect>
      <x>80</x>
      <y>20</y>
      <width>81</width>
      <height>20</height>
     </rect>
    </property>
   </widget>
   <widget class="QPushButton" name="pushButton">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>60</y>
      <width>75</width>
      <height>23</height>
     </rect>
    </property>
    <property name="text">
     <string>查找</string>
    </property>
   </widget>
   <widget class="QPushButton" name="pushButton_2">
    <property name="geometry">
     <rect>
      <x>110</x>
      <y>60</y>
      <width>75</width>
      <height>23</height>
     </rect>
    </property>
    <property name="text">
     <string>删除</string>
    </property>
   </widget>
   <widget class="QLabel" name="label_2">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>140</y>
      <width>54</width>
      <height>12</height>
     </rect>
    </property>
    <property name="text">
     <string>书名:</string>
    </property>
   </widget>
   <widget class="QLabel" name="label_3">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>170</y>
      <width>54</width>
      <height>12</height>
     </rect>
    </property>
    <property name="text">
     <string>作者:</string>
    </property>
   </widget>
   <widget class="QLineEdit" name="lineEdit_2">
    <property name="geometry">
     <rect>
      <x>50</x>
      <y>140</y>
      <width>113</width>
      <height>20</height>
     </rect>
    </property>
   </widget>
   <widget class="QLineEdit" name="lineEdit_3">
    <property name="geometry">
     <rect>
      <x>50</x>
      <y>170</y>
      <width>113</width>
      <height>20</height>
     </rect>
    </property>
   </widget>
   <widget class="QPushButton" name="pushButton_3">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>210</y>
      <width>75</width>
      <height>23</height>
     </rect>
    </property>
    <property name="text">
     <string>更新</string>
    </property>
   </widget>
   <widget class="QPushButton" name="pushButton_4">
    <property name="geometry">
     <rect>
      <x>110</x>
      <y>210</y>
      <width>75</width>
      <height>23</height>
     </rect>
    </property>
    <property name="text">
     <string>添加</string>
    </property>
   </widget>
   <widget class="QPushButton" name="pushButton_5">
    <property name="geometry">
     <rect>
      <x>250</x>
      <y>190</y>
      <width>101</width>
      <height>41</height>
     </rect>
    </property>
    <property name="text">
     <string>显示全部</string>
    </property>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menuBar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>400</width>
     <height>22</height>
    </rect>
   </property>
  </widget>
  <widget class="QToolBar" name="mainToolBar">
   <attribute name="toolBarArea">
    <enum>TopToolBarArea</enum>
   </attribute>
   <attribute name="toolBarBreak">
    <bool>false</bool>
   </attribute>
  </widget>
  <widget class="QStatusBar" name="statusBar"/>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>



已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页