Qt 读取和写入xml文件工程示例、xml的特点

xml叫做可扩展标记语言,常被用在互联网数据传输中。

特点:是与操作系统、编程语言都无关,可以实现不同系统间的数据传输。

编写格式:举例

<?xml version = "1.0" encoding = "UTF-8"?>
<FanTest>
 <teacher>
  <TName>姓名</TName>
  <TSChool>学校</TSChool>
  <TAge>年龄</TAge>
  <TClass>班级</TClass>
 </teacher>
</FanTest>
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

一个xml文档必须要有第一行的声明和它的文档元素的描述信息就可以了。

<?xml version = "1.0" encoding = "UTF-8"?>
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

version是指版本,encoding是文档编码格式

<TName>姓名</TName>

<TName>是标签开始,</TName>是标签结束,姓名是内容

qt实现对xml文档的读取和写入代码示例

pro文件

#-------------------------------------------------
#
# Project created by QtCreator 2022-03-12T23:29:33
#
#-------------------------------------------------

QT       += core gui xml

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = WriteAndReadxml
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

CONFIG += c++11

SOURCES += \
        main.cpp \
        writenandreadxml.cpp

HEADERS += \
        writenandreadxml.h

FORMS += \
        writenandreadxml.ui

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

新建一个带ui的程序,以QDialog为基类,记住在配置文件中加入xml模块。

.h 文件

#ifndef WRITENANDREADXML_H
#define WRITENANDREADXML_H

#include <QDialog>
#include <QFile>
#include <QDomNodeList>
namespace Ui {
class WritenAndReadxml;
}

class WritenAndReadxml : public QDialog
{
    Q_OBJECT

public:
    explicit WritenAndReadxml(QWidget *parent = nullptr);
    ~WritenAndReadxml();

public:
    void writeXml();//写入xml数据到xml文件
    void readXml();//读取xml文件
    bool openXml(QString &fileNamePath);//打开xml文件
    void readRootXml(QDomNodeList &sonNodeLists);//处理子节点集
private slots:
    void on_Write_clicked();

    void on_Read_clicked();

private:
    Ui::WritenAndReadxml *ui;
    QFile m_file;
    QString currentFilePath;//当前文件路径
    QString currentFileName;//当前文件名字

};

#endif // WRITENANDREADXML_H

m_file用于第一步读取xml文件,或者最后的保存,

currentFilePath 当前文件路径 currentFileName当前文件名字

.cpp 文件

#include "writenandreadxml.h"
#include "ui_writenandreadxml.h"
#include <QDebug>
#include <QDomDocument>
WritenAndReadxml::WritenAndReadxml(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::WritenAndReadxml)
{
    ui->setupUi(this);
    currentFilePath = QCoreApplication::applicationDirPath();//当前文件路径
    currentFileName = "/Qt.xml";

}

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

void WritenAndReadxml::writeXml()
{
    if(!openXml(currentFileName))//如果打开失败,没有则创建xml文件
    {
        qDebug()<<"写入文件失败!!";
        return;
    }
    qDebug()<<"写入文件成功!!";
    QDomDocument domDoc;
    QDomProcessingInstruction version;
    version = domDoc.createProcessingInstruction("xml","version = \"1.0\" encoding = \"UTF-8\"");
    domDoc.appendChild(version);

    QDomElement domRootElement = domDoc.createElement("FanTest");
    domDoc.appendChild(domRootElement);

    QDomElement itemRootElement = domDoc.createElement("teacher");
    {
        QDomElement node1 = domDoc.createElement("TName");//创建子节点
        QDomText domText1 = domDoc.createTextNode("TName");
        domText1.setData(QString::fromLocal8Bit("姓名"));//设置子节点数据
        node1.appendChild(domText1);//将子节点数据绑定
        itemRootElement.appendChild(node1);//将子节点挂到父节点上

        QDomElement node2 = domDoc.createElement("TSChool");//创建子节点
        QDomText domText2 = domDoc.createTextNode("TSChool");
        domText2.setData(QString::fromLocal8Bit("学校"));//设置子节点数据
        node2.appendChild(domText2);//将子节点数据绑定
        itemRootElement.appendChild(node2);//将子节点挂到父节点上

        QDomElement node3 = domDoc.createElement("TAge");//创建子节点
        QDomText domText3 = domDoc.createTextNode("TAge");
        domText3.setData(QString::fromLocal8Bit("年龄"));//设置子节点数据
        node3.appendChild(domText3);//将子节点数据绑定
        itemRootElement.appendChild(node3);//将子节点挂到父节点上

        QDomElement node4 = domDoc.createElement("TClass");//创建子节点
        QDomText domText4 = domDoc.createTextNode("TClass");
        domText4.setData(QString::fromLocal8Bit("班级"));//设置子节点数据
        node4.appendChild(domText4);//将子节点数据绑定
        itemRootElement.appendChild(node4);//将子节点挂到父节点上
    }
    domRootElement.appendChild(itemRootElement);
    m_file.write(domDoc.toString().toLocal8Bit().data());
    m_file.close();
}

void WritenAndReadxml::readXml()
{
    if(!openXml(currentFileName))
    {
        qDebug()<<"Read Open false";
    }
    qDebug()<<"Read Open true";

    QDomDocument doc;
    if(!doc.setContent(&m_file))
    {
        m_file.close();
        qDebug()<<"Read xml false";
        return;
    }
    qDebug()<<"Read xml true";
    QDomElement root = doc.documentElement();
    QDomNode node = root.firstChild();
    while (!node.isNull())
    {
        QDomNodeList nodelists = node.childNodes();
        QString root = node.toElement().tagName();

        if(root == "teacher")
        {
            readRootXml(nodelists);
        }
        node = node.nextSibling(); //读取下一个父节点
    }

}

bool WritenAndReadxml::openXml(QString &fileNamePath)
{
    m_file.setFileName(currentFilePath+"./"+fileNamePath);
    qDebug()<<currentFilePath+fileNamePath;
    return m_file.open(QIODevice::ReadWrite | QFile::Text);

}

void WritenAndReadxml::readRootXml(QDomNodeList &sonNodeLists)
{
    for (int i =0;i<sonNodeLists.size();i++)
    {
        QDomElement sonElement = sonNodeLists.at(i).toElement();
        if(sonElement.toElement().tagName().compare("TName")==0)
        {
            qDebug()<<sonElement.text();
        }
        else if (sonElement.toElement().tagName().compare("TSChool")==0)
        {
            qDebug()<<sonElement.text();
        }
        else if (sonElement.toElement().tagName().compare("TAge")==0)
        {
            qDebug()<<sonElement.text();
        }
        else if (sonElement.toElement().tagName().compare("TClass")==0)
        {
            qDebug()<<sonElement.text();
        }
    }
}

void WritenAndReadxml::on_Write_clicked()
{
    writeXml();
}

void WritenAndReadxml::on_Read_clicked()
{
    readXml();
}

.ui文件

保存的文件如下:

 

借鉴了多个前人的研究成果。

 

  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值