Qt 操作QDomDocument对象修改节点

来源:互联网 发布:传淘宝工具怎么使用 编辑:程序博客网 时间:2024/06/07 10:27

代码部分:

QFile file(filePath);

if (!file.open(QFile::ReadOnly | QFile::Text)) 
{
QMessageBox::critical(NULL,tr("错误"),tr("无法打开%1文件").arg(filePath),QMessageBox::Ok);
return;
}
QString error;
int row = 0;
int col= 0 ;
QDomDocument dom;
if (!dom.setContent(&file, false, &error, &row, &col))
{
QMessageBox::warning(0, tr("error"), tr("错误%1, 行%2, 列%3").arg(error).arg(row).arg(col), QMessageBox::Yes);
file.close();
return;
}

QDomElement root = dom.documentElement();// 根节点
QDomNodeList nlist = root.elementsByTagName("tag"); //要修改的tag
for (int i=0; i<nlist.count(); i++)
{

QDomElement ele = nlist.at(i).toElement();

//关键1

QDomNode oldNode = ele.firstChild(); //旧节点
ele.firstChild().setNodeValue(QString::number(channel)); //改值
QDomNode newNode = ele.firstChild(); //新节点
ele.replaceChild(newNode, oldNode); //替换
}

file.close();

//关键2

QFile wfile(filePath);
if (!wfile.open(QIODevice::WriteOnly))
{
QMessageBox::critical(NULL,tr("错误"),tr("无法打开%1文件").arg(filePath),QMessageBox::Ok);
return;
}
QTextStream out(&wfile);
QString save = dom.toString();
out << dom.toString();

wfile.close();


用一个dom对象,两个文件对象, 一个读打开修改,令一个重写, 直接修改不成功.

0 0
原创粉丝点击