Qt 操做QDomDocument對象修改節點

 

版權聲明:本文爲博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處連接和本聲明。
本文連接: https://blog.csdn.net/liulihuo_gyh/article/details/41321369

代碼部分:html

QFile file(filePath);dom

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();spa

//關鍵1.net

QDomNode oldNode = ele.firstChild(); //舊節點
ele.firstChild().setNodeValue(QString::number(channel)); //改值
QDomNode newNode = ele.firstChild(); //新節點
ele.replaceChild(newNode, oldNode); //替換
}

file.close();htm

//關鍵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();blog

 

用一個dom對象,兩個文件對象, 一個讀打開修改,令一個重寫, 直接修改不成功.element

相關文章
相關標籤/搜索