QT xml文件

QT/qt(17)xml文件

XML(可扩展标记语言,eXtensible Markup Language)
是一种用于存储和传输数据的标记语言。

它被设计用来结构化、存储和传输信息,具有自我描述性,
易于阅读和理解。XML 文件通常用于数据交换、配置文件、文档格式等领域。

XML 文件由一系列的元素(elements)组成,
每个元素由开始标签(start tag)、内容(content)和结束标签(end tag)组成。

元素可以包含属性(attributes)和其他子元素。

<person>
    <name>John Doe</name>
    <age>30</age>
    <city>New York</city>
    <address>
        <street>123 Main St</street>
        <state>NY</state>
        <city>New York</city>
    </address>
</person>

在这个示例中:

<person> 是根元素。
<name>, <age>, <city>, 和 <address> 是子元素。
<address> 元素包含 <street>, <state>, 和 <city> 子元素。


XML 文件的特点包括:

可扩展性:XML 允许用户定义自己的标签和结构,因此非常灵活。
自我描述性:XML 文件包含了数据的结构和含义,易于人类阅读和理解。
平台无关性:XML 文件可以在不同的操作系统和应用程序之间交换数据。
层次结构:XML 数据以树形结构组织,便于数据的存储和检索。


XML 文件通常用于以下场景:

数据交换:不同系统之间交换数据,如 Web 服务、API 等。
配置文件:应用程序的配置信息,如服务器配置、应用程序设置等。
文档格式:用于定义文档的结构和内容,如 SVG(可缩放矢量图形)、RSS(简易信息聚合)等。

QDomDocument 类

这些成员函数涵盖了 QDomDocument 类的基本功能,包括创建节点、解析 XML、操作文档结构、查询和遍历节点等。

// 构造函数
QDomDocument::QDomDocument(); // 构造一个空的 QDomDocument 对象
QDomDocument::QDomDocument(const QDomDocumentType &doctype); // 构造一个 QDomDocument 对象,并指定文档类型
QDomDocument::QDomDocument(const QDomDocument &x); // 通过复制另一个 QDomDocument 对象 x 来构造一个 QDomDocument 对象

// 创建节点
QDomElement QDomDocument::createElement(const QString &tagName); // 创建一个元素节点
QDomComment QDomDocument::createComment(const QString &data); // 创建一个注释节点
QDomText QDomDocument::createTextNode(const QString &data); // 创建一个文本节点
QDomCDATASection QDomDocument::createCDATASection(const QString &data); // 创建一个 CDATA 节点
QDomProcessingInstruction QDomDocument::createProcessingInstruction(const QString &target, const QString &data); // 创建一个处理指令节点
QDomDocumentFragment QDomDocument::createDocumentFragment(); // 创建一个文档片段节点
QDomAttribute QDomDocument::createAttribute(const QString &name); // 创建一个属性节点
QDomEntityReference QDomDocument::createEntityReference(const QString &name); // 创建一个实体引用节点

// 解析 XML
bool QDomDocument::setContent(const QByteArray &data, bool namespaceProcessing, QString *errorMsg = nullptr, int *errorLine = nullptr, int *errorColumn = nullptr); // 从字节数组中解析 XML 内容
bool QDomDocument::setContent(const QString &data, bool namespaceProcessing, QString *errorMsg = nullptr, int *errorLine = nullptr, int *errorColumn = nullptr); // 从字符串中解析 XML 内容
bool QDomDocument::setContent(QIODevice *dev, bool namespaceProcessing, QString *errorMsg = nullptr, int *errorLine = nullptr, int *errorColumn = nullptr); // 从 QIODevice 中解析 XML 内容
bool QDomDocument::setContent(const QByteArray &data, QString *errorMsg = nullptr, int *errorLine = nullptr, int *errorColumn = nullptr); // 从字节数组中解析 XML 内容,不进行命名空间处理
bool QDomDocument::setContent(const QString &data, QString *errorMsg = nullptr, int *errorLine = nullptr, int *errorColumn = nullptr); // 从字符串中解析 XML 内容,不进行命名空间处理
bool QDomDocument::setContent(QIODevice *dev, QString *errorMsg = nullptr, int *errorLine = nullptr, int *errorColumn = nullptr); // 从 QIODevice 中解析 XML 内容,不进行命名空间处理

// 获取文档内容
QString QDomDocument::toString(int indent) const; // 将文档转换为字符串
QDomElement QDomDocument::documentElement() const; // 返回文档的根元素
QDomNode QDomDocument::firstChild() const; // 返回文档的第一个子节点
QDomNode QDomDocument::lastChild() const; // 返回文档的最后一个子节点
QDomNode QDomDocument::childNodes() const; // 返回文档的所有子节点

// 操作文档
QDomNode QDomDocument::appendChild(const QDomNode &newChild); // 将一个节点添加到文档的子节点列表中
QDomNode QDomDocument::insertBefore(const QDomNode &newChild, const QDomNode &refChild); // 在指定节点之前插入一个新节点
QDomNode QDomDocument::replaceChild(const QDomNode &newChild, const QDomNode &oldChild); // 替换指定节点
QDomNode QDomDocument::removeChild(const QDomNode &oldChild); // 移除指定节点
QDomNode QDomDocument::cloneNode(bool deep = true) const; // 克隆节点

// 查询和遍历
QDomNode QDomDocument::firstChildElement(const QString &tagName = QString()) const; // 返回第一个子元素节点
QDomNode QDomDocument::lastChildElement(const QString &tagName = QString()) const; // 返回最后一个子元素节点
QDomNode QDomDocument::elementsByTagName(const QString &tagname) const; // 返回所有具有指定标签名的元素节点
QDomNode QDomDocument::elementsByTagNameNS(const QString &nsURI, const QString &localName) const; // 返回所有具有指定命名空间和本地名称的元素节点
QDomNode QDomDocument::importNode(const QDomNode &importedNode, bool deep = true); // 导入节点

// 文档类型
QDomDocumentType QDomDocument::doctype() const; // 返回文档类型
QDomImplementation QDomDocument::implementation() const; // 返回文档的实现

// 命名空间
QString QDomDocument::namespaceURI() const; // 返回文档的命名空间 URI
QString QDomDocument::prefix() const; // 返回文档的前缀
QString QDomDocument::localName() const; // 返回文档的本地名称

// 其他
bool QDomDocument::isDocument() const; // 判断节点是否为文档节点
bool QDomDocument::isNull() const; // 判断节点是否为空
QDomDocument &QDomDocument::operator=(const QDomDocument &x); // 赋值运算符

QDomComment 类 用于表示 XML 文档中的注释节点

class QDomComment {
public:
    // 构造函数
    QDomComment(); // 构造一个空的 QDomComment 对象
    QDomComment(const QDomComment &x); // 构造一个 QDomComment 对象,通过复制另一个 QDomComment 对象 x

    // 公共函数
    QDomComment &operator=(const QDomComment &x); // 赋值运算符,将另一个 QDomComment 对象 x 赋值给当前对象
    void swap(QDomComment &other); // 交换当前对象和另一个 QDomComment 对象 other 的内容
    QString data() const; // 返回注释节点的文本内容
    void setData(const QString &d); // 设置注释节点的文本内容为 d

    // 友元函数
    friend bool operator==(const QDomComment &lhs, const QDomComment &rhs); // 比较两个 QDomComment 对象是否相等
    friend bool operator!=(const QDomComment &lhs, const QDomComment &rhs); // 比较两个 QDomComment 对象是否不相等

    // 继承自 QDomNode 的函数
    QDomNode::NodeType nodeType() const; // 返回节点的类型,对于 QDomComment 对象,返回 QDomNode::CommentNode
    QDomNode cloneNode(bool deep = true) const; // 克隆当前节点,deep 参数表示是否深度克隆
    QDomDocument ownerDocument() const; // 返回当前节点所属的文档
    QDomNode parentNode() const; // 返回当前节点的父节点
    QDomNodeList childNodes() const; // 返回当前节点的子节点列表
    QDomNode firstChild() const; // 返回当前节点的第一个子节点
    QDomNode lastChild() const; // 返回当前节点的最后一个子节点
    QDomNode previousSibling() const; // 返回当前节点的前一个兄弟节点
    QDomNode nextSibling() const; // 返回当前节点的后一个兄弟节点
    QDomNamedNodeMap attributes() const; // 返回当前节点的属性列表(对于注释节点,通常为空)
    QDomNode insertBefore(const QDomNode &newChild, const QDomNode &refChild); // 在指定子节点之前插入新节点
    QDomNode insertAfter(const QDomNode &newChild, const QDomNode &refChild); // 在指定子节点之后插入新节点
    QDomNode replaceChild(const QDomNode &newChild, const QDomNode &oldChild); // 替换指定的子节点
    QDomNode removeChild(const QDomNode &oldChild); // 移除指定的子节点
    QDomNode appendChild(const QDomNode &newChild); // 在当前节点的子节点列表末尾添加新节点
    bool hasChildNodes() const; // 判断当前节点是否有子节点
    QDomNode normalize() const; // 规范化当前节点及其子节点
    bool isSupported(const QString &feature, const QString &version) const; // 判断当前节点是否支持指定的特性和版本
    QString namespaceURI() const; // 返回当前节点的命名空间 URI
    QString prefix() const; // 返回当前节点的命名空间前缀
    void setPrefix(const QString &pre); // 设置当前节点的命名空间前缀
    QString localName() const; // 返回当前节点的本地名称
    bool hasAttributes() const; // 判断当前节点是否有属性
    QString nodeName() const; // 返回当前节点的名称
    QString nodeValue() const; // 返回当前节点的值
    void setNodeValue(const QString &v); // 设置当前节点的值
    QDomNode::NodeType nodeType() const; // 返回当前节点的类型
    QDomNode namedItem(const QString &name) const; // 返回具有指定名称的子节点
};

示例

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <QLabel>
#include <QLineEdit>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QComboBox>
#include <QPushButton>
#include <QDomDocument>//xml解析
#include <QDomComment>//xml注释
#include <QFile>//文件操作
#include <QDir>


class Dialog : public QDialog
{
    Q_OBJECT

public:
    Dialog(QWidget *parent = nullptr);
    ~Dialog();

private:

    //垂直布局

    QHBoxLayout *vlayout ;
    //水平布局

    QVBoxLayout *hlayout1 ;
    QVBoxLayout *hlayout2 ;

    QLabel *numberLabel ;//职工编号
    QLineEdit *numberEdit ;//职工编号输入框
    QLabel *nameLabel ;//职工姓名
    QLineEdit *nameEdit ;//职工姓名输入框
    QLabel *ageLabel ;//职工年龄
    QLineEdit *ageEdit ;//职工年龄输入框
    QLabel *genderLabel ;//职工性别
    QComboBox *genderEdit ;//职工性别输入框
    QLabel *phoneLabel ;//职工电话
    QLineEdit *phoneEdit ;//职工电话输入框
    QLabel *departmentLabel ;//职工部门
    QLineEdit *departmentEdit ;//职工部门输入框
    QLabel *positionLabel ;//职工职位
    QLineEdit *positionEdit ;//职工职位输入框
    QLabel *salaryLabel ;//职工薪资
    QLineEdit *salaryEdit ;//职工薪资输入框

    //展示框
    QLabel *numberLabelshow ;//职工编号
    QLineEdit *numberEditshow ;//职工编号输入框
    QLabel *nameLabelshow ;//职工姓名
    QLineEdit *nameEditshow ;//职工姓名输入框
    QLabel *ageLabelshow ;//职工年龄
    QLineEdit *ageEditshow ;//职工年龄输入框
    QLabel *genderLabelshow ;//职工性别
    QComboBox *genderEditshow ;//职工性别输入框
    QLabel *phoneLabelshow ;//职工电话
    QLineEdit *phoneEditshow ;//职工电话输入框
    QLabel *departmentLabelshow ;//职工部门
    QLineEdit *departmentEditshow ;//职工部门输入框
    QLabel *positionLabelshow ;//职工职位
    QLineEdit *positionEditshow ;//职工职位输入框
    QLabel *salaryLabelshow ;//职工薪资
    QLineEdit *salaryEditshow ;//职工薪资输入框


    QPushButton *addButton ;//添加按钮
    QPushButton *selectButton ;//查询按钮


    QFile *file ;//文件操作
    QString filePath ;//文件路径


public:
    bool openFile(QString filePath);

    //读取子节点
    void readrootxml(QDomNodeList doc);

public slots:
    void readxml();//读取xml文件
    //写入

    void writexml();//写入xml文件
};
#endif // DIALOG_H

#include "dialog.h"
#include "./ui_dialog.h"

Dialog::Dialog(QWidget *parent)
    : QDialog(parent)

{

    //设置布局
    vlayout = new QHBoxLayout(this);
    //设置垂直布局
    hlayout1 = new QVBoxLayout();
    numberLabel=new QLabel("编号:");
    numberEdit=new QLineEdit();

    nameLabel=new QLabel("姓名:");
    nameEdit=new QLineEdit();
    ageLabel=new QLabel("年龄:");
    ageEdit=new QLineEdit();
    genderLabel=new QLabel("性别:");
    genderEdit=new QComboBox();
    genderEdit->addItem("男");
    genderEdit->addItem("女");
    phoneLabel=new QLabel("电话:");
    phoneEdit=new QLineEdit();
    departmentLabel=new QLabel("部门:");
    departmentEdit=new QLineEdit();
    positionLabel=new QLabel("职位:");
    positionEdit=new QLineEdit();
    salaryLabel=new QLabel("薪水:");
    salaryEdit=new QLineEdit();
    hlayout1->addWidget(numberLabel);
    hlayout1->addWidget(numberEdit);
    hlayout1->addWidget(nameLabel);
    hlayout1->addWidget(nameEdit);
    hlayout1->addWidget(ageLabel);
    hlayout1->addWidget(ageEdit);
    hlayout1->addWidget(genderLabel);
    hlayout1->addWidget(genderEdit);
    hlayout1->addWidget(phoneLabel);
    hlayout1->addWidget(phoneEdit);
    hlayout1->addWidget(departmentLabel);
    hlayout1->addWidget(departmentEdit);
    hlayout1->addWidget(positionLabel);
    hlayout1->addWidget(positionEdit);
    hlayout1->addWidget(salaryLabel);
    hlayout1->addWidget(salaryEdit);

    addButton=new QPushButton("添加");
    hlayout1->addWidget(addButton);
    vlayout->addLayout(hlayout1);

    numberLabelshow=new QLabel("编号:");
    numberEditshow=new QLineEdit();
    nameLabelshow=new QLabel("姓名:");
    nameEditshow=new QLineEdit();
    ageLabelshow=new QLabel("年龄:");
    ageEditshow=new QLineEdit();
    genderLabelshow=new QLabel("性别:");
    genderEditshow=new QComboBox();
    genderEditshow->addItem("男");
    genderEditshow->addItem("女");
    phoneLabelshow=new QLabel("电话:");
    phoneEditshow=new QLineEdit();
    departmentLabelshow=new QLabel("部门:");
    departmentEditshow=new QLineEdit();
    positionLabelshow=new QLabel("职位:");
    positionEditshow=new QLineEdit();
    salaryLabelshow=new QLabel("薪水:");
    salaryEditshow=new QLineEdit();
    hlayout2=new QVBoxLayout();
    hlayout2->addWidget(numberLabelshow);
    hlayout2->addWidget(numberEditshow);
    hlayout2->addWidget(nameLabelshow);
    hlayout2->addWidget(nameEditshow);
    hlayout2->addWidget(ageLabelshow);
    hlayout2->addWidget(ageEditshow);
    hlayout2->addWidget(genderLabelshow);
    hlayout2->addWidget(genderEditshow);
    hlayout2->addWidget(phoneLabelshow);
    hlayout2->addWidget(phoneEditshow);
    hlayout2->addWidget(departmentLabelshow);
    hlayout2->addWidget(departmentEditshow);
    hlayout2->addWidget(positionLabelshow);
    hlayout2->addWidget(positionEditshow);
    hlayout2->addWidget(salaryLabelshow);
    hlayout2->addWidget(salaryEditshow);

    selectButton=new QPushButton("查询");
    hlayout2->addWidget(selectButton);
    vlayout->addLayout(hlayout2);



    filePath ="./employee.xml";//设置文件路径

    connect(addButton,SIGNAL(clicked()),
            this,SLOT(writexml()));


    connect(selectButton,SIGNAL(clicked()),
            this,SLOT(readxml()));
}

Dialog::~Dialog()
{

}


bool  Dialog::openFile(QString filePath){
    //打开文件
    file=new QFile(filePath);
    if(!file->open(QIODevice::ReadWrite | QIODevice::Text)){
        qDebug()<<"open file error";
        return false;
    }
    return true;
}
void  Dialog::readxml(){
    if(!openFile(filePath)){
        qDebug()<<"open file error";
        return;
    }
    qDebug()<<"read xml";


    QDomDocument doc;

    if(!doc.setContent(file)){//读取xml文件内容
        qDebug()<<"read xml error";
        file->close();
        return;
    }


    QDomElement root=doc.documentElement();//获取根节点


    QDomNode node=root.firstChild();//获取第一个子节点
    while (!node.isNull()){//遍历所有子节点
        QDomNodeList list=node.childNodes();//获取子节点列表
        QString name=node.nodeName();//获取节点名称
        if(name=="employee") {//判断节点名称是否为employee
            //调用读取子节点信息函数

            readrootxml(list);
        }
        node=node.nextSibling();//获取下一个子节点
    }

}



void  Dialog::writexml(){

    if(!openFile(filePath)){
        qDebug()<<"open file error";
        return;
    }
    qDebug()<<"read xml";



    QDomDocument doc;//创建文档对象
    QDomProcessingInstruction instruction;//创建处理指令对象
    instruction=doc.createProcessingInstruction("xml","version='1.0' encoding='UTF-8'");//创建处理指令
    doc.appendChild(instruction);//添加处理指令

    QDomElement root=doc.createElement("employees");//创建根节点
    doc.appendChild(root);//添加根节点

    QDomElement employee=doc.createElement("employee");//创建employee节点
    root.appendChild(employee);//添加employee节点

    QDomElement number=doc.createElement("number");//创建number节点
    number.appendChild(doc.createTextNode(numberEdit->text()));//添加number节点内容
    employee.appendChild(number);//添加number节点


    QDomElement name=doc.createElement("name");//创建name节点
    name.appendChild(doc.createTextNode(nameEdit->text()));//添加name节点内容
    employee.appendChild(name);//添加name节点

    QDomElement age=doc.createElement("age");//创建age节点
    age.appendChild(doc.createTextNode(ageEdit->text()));//添加age节点内容
    employee.appendChild(age);//添加age节点

    QDomElement gender=doc.createElement("gender");//创建gender节点
    gender.appendChild(doc.createTextNode(genderEdit->currentText()));//添加gender节点内容
    employee.appendChild(gender);//添加gender节点



    QDomElement phone=doc.createElement("phone");//创建phone节点
    phone.appendChild(doc.createTextNode(phoneEdit->text()));//添加phone节点内容
    employee.appendChild(phone);//添加phone节点



    QDomElement department=doc.createElement("department");//创建department节点
    department.appendChild(doc.createTextNode(departmentEdit->text()));//添加department节点内容
    employee.appendChild(department);//添加department节点



    QDomElement position=doc.createElement("position");//创建position节点
    position.appendChild(doc.createTextNode(positionEdit->text()));//添加position节点内容
    employee.appendChild(position);//添加position节点



    QDomElement salary=doc.createElement("salary");//创建salary节点
    salary.appendChild(doc.createTextNode(salaryEdit->text()));//添加salary节点内容
    employee.appendChild(salary);//添加salary节点



    file->write( doc.toString().toUtf8().data());

    file->close();
}


void Dialog::readrootxml(QDomNodeList doc){
    //读取根节点信息
    for(int i=0;i<doc.count();i++){
        //获取子节点
        QDomNode node=doc.item(i);
        //获取节点名称
        QString name=node.nodeName();
        //判断节点名称
        if(name=="number"){
            numberEditshow->setText(node.firstChild().nodeValue());
        }else if(name=="name"){
            nameEditshow->setText(node.firstChild().nodeValue());
        }else if(name=="age"){
            ageEditshow->setText(node.firstChild().nodeValue());
        }else if(name=="gender"){
            genderEditshow->setCurrentText(node.firstChild().nodeValue());
        }else if(name=="phone"){
            phoneEditshow->setText(node.firstChild().nodeValue());
        }else if(name=="department"){
            departmentEditshow->setText(node.firstChild().nodeValue());
        }else if(name=="position"){
            positionEditshow->setText(node.firstChild().nodeValue());
        }else if(name=="salary"){
            salaryEditshow->setText(node.firstChild().nodeValue());
        }

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

可能只会写BUG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值