需要在.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>