代码部分:

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对象,两个文件对象, 一个读打开修改,令一个重写, 直接修改不成功.