如果文件不存在,则读取XML文件或使用根元素创建新文件

时间:2014-11-20 16:02:51

标签: qt qfile

我需要在程序的构造函数中创建一个QDomElement,其中包含我的XML文件的根元素。

为此,程序首先尝试读取文件。如果无法读取文件,则将使用根元素创建新文件。在此之后,我得到了我的文件的根元素。

以下是我的代码:

bool hadToCreateXML=false;
bool wasLoadedCorrectly=false;
fileXML.setFileName("C:/logs.xml");
if(!fileXML.open(QIODevice::ReadOnly | QIODevice::Text)){
    cout << "fail open, file does not exsist?" << endl;
    if(!fileXML.open(QIODevice::WriteOnly | QIODevice::Text)){
        cout << "failed creating file" << endl;
    }
    else{
        ui->outputText->append("First time running");
        hadToCreateXML=true;
        QDomDocument tempFirstTime;
        tempFirstTime.setContent(&fileXML);
        tempFirstTime.createElement("MyRoot");
        QTextStream stream(&fileXML);
        stream << tempFirstTime.toString();
        fileXML.close();
    }
}
else wasLoadedCorrectly=true;

if(hadToCreateXML||wasLoadedCorrectly){
    if(!documentXML.setContent(&fileXML)){
        cout << "failed to load doc" << endl;
    }
    else {
        rootXML=documentXML.firstChildElement();
        fileXML.close();
    }
}

它看起来很乱,不幸的是,这并没有按预期工作。如果文件不存在,则会创建该文件,但不会将根元素添加到该文件中。我做错了什么?

1 个答案:

答案 0 :(得分:1)

使用类似的东西:

QFile fileXML;
bool hadToCreateXML=false;
bool wasLoadedCorrectly=false;
fileXML.setFileName("G:/logs.txt");
    if(!fileXML.open(QIODevice::WriteOnly | QIODevice::Text)){
        qDebug() << "failed creating file" << endl;
    }
    else{
        hadToCreateXML=true;
        QDomDocument tempFirstTime;
        //tempFirstTime.setContent(&fileXML); don't use
        tempFirstTime.appendChild(tempFirstTime.createElement("MyRoot"));
        QTextStream stream(&fileXML);
        stream << tempFirstTime.toString();
        qDebug() << "data "<< tempFirstTime.toString();
        fileXML.close();
    }

您的错误:您将文件打开为WriteOnly但尝试拨打setContent,尝试读取文件,禁止播放。您将收到下一个调试错误:

  

QIODevice :: read:WriteOnly device

还可以使用QFile::exists()检查文件是否存在。

所以你的代码应该是这样的:

if(fileXML.exists())
    //read
else
    //write

http://qt-project.org/doc/qt-5/qfile.html#exists-2

相关问题