QT通过DOM 读写XML的一个小问题

2014-11-24 12:11:44 · 作者: · 浏览: 2

最近做一个背单词的小东东,需要在指定日期提示信息,用到了xml.工程不大,自然使用DOM.


工程中需要在指定日期中插入提示信息,最开始的想法是"查找+插入"的模式,需要同时读写操作,因此


QFile file("struct.xml");
if (!file.open(QFile::ReadWrite )){return;}


更改完毕后


QTextStream out(&fileWrite);
doc.save(out,3);
fileWrite.close();


程序运行,没有错误提示.


但是最终得到的xml文件如下




Old





Old
New


显然第一段是需要被替换,不应该出现的.调整了以下思路,更改程序如下


QFile fileRead("struct.xml");
if (!fileRead.open(QFile::ReadOnly )){return;} ///只读模式打开文件



QString errorStr;
int errorLine;
int errorColumn;


QDomDocument doc;
if (!doc.setContent(&fileRead, false, &errorStr, &errorLine, ///把fileRead塞进一个QDomDocument
&errorColumn)) {
qDebug() << "Error: Parse error at line " << errorLine << ", "
<< "column " << errorColumn << ": "
<< qPrintable(errorStr) ;
return ;//false;
}


fileRead.close(); ///过河拆桥,关掉fileRead


更改完毕后


QFile fileWrite("struct.xml");


if(!fileWrite.open(QIODevice::WriteOnly | QIODevice::Truncate)) return ; ///写入模式打开文件
QTextStream out(&fileWrite);



doc.save(out,3);
fileWrite.close();