Read XML file or create new one with root element if file doesn't exist

562 views Asked by At

I need to create a QDomElement with the root element of my XML file in the constructor of my program.

For this the program first tries to read the file. If the file can't be read a new file will be created with the root element. After this I get the root element of my file.

Following is my code for this:

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

It looks messy and unfortunately this doesn't work as intended. If the file doesn't exist it will be created but the root element will not be added to it. What am I doing wrong?

1

There are 1 answers

0
Jablonski On BEST ANSWER

Use something like this:

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

Your mistakes: you opened file as WriteOnly but try to call setContent, you try to read file, it is forbidden. You will get next debug error:

QIODevice::read: WriteOnly device

Also use QFile::exists() to check is file exist.

So your code should be something like:

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

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