Qt中xml模块的使用

需要在.pro中添加模块 xml

#include "widget.h"
#include "ui_widget.h"

#include <QFile>
#include <QDomDocument>
#include <QDomElement>
#include <QTextStream>
#include <QDir>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
}

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

//删除字符串中所有特定的字符
void Widget::delchar(QString &data, const QChar &c)
{
    int index = data.indexOf(c);
    while (index != -1)
    {
        data.remove(index,1);
        index = data.indexOf(c,index);
    }
}

void Widget::on_pushButton_clicked()
{
    QDir dir("D://xml");
    auto filenamelist = dir.entryList(QDir::Files);

    for(auto filename : filenamelist)
    {

        QString newfilename = filename;
        //处理文件内容
        // 读取XML文件
        QDomDocument doc;
        QString filepath = "D://xml//" + filename;
        QFile file(filepath);
        // qDebug() << filepath;
        if (!file.open(QIODevice::ReadOnly) || !doc.setContent(&file)) 	{
            qDebug() << "无法打开或解析XML文件。";
            return ;
        }

        file.close();

        // 查找目标节点并修改内容
        QDomElement root = doc.documentElement();
        QDomElement hello = root.firstChildElement("hello");
        QDomElement data = hello.firstChildElement("data");
        
        QString datastr = data.attribute("info");
        delchar(datastr,';');

        data.setAttribute("info",datastr);
        QDomText newText = doc.createTextNode("123");
        data.appendChild(newText);

        // 保存修改后的XML文件
        if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
            qDebug() << "无法打开XML文件以写入。";
            return;
        }

        QTextStream out(&file);
        doc.save(out, 4); // 4表示文档格式缩进
        file.close();

        //处理文件名
        delchar(newfilename,';');
        dir.rename(filename,newfilename);
    }

    QMessageBox::information(this,"提示","修改完成");
}


该程序实现了对dir目录下所有xml文件名和文件中hello/data节点的属性info中存在的’;'进行了处理

1;2;3.xml —> 123.xml

<hello>
	<data info="hello;;;wor;;ld">
	</data>
</hello>

----->

<hello>
	<data info="helloworld">
	</data>
</hello>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值