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?
Use something like this:
Your mistakes: you opened file as
WriteOnly
but try to callsetContent
, you try to read file, it is forbidden. You will get next debug error:Also use
QFile::exists()
to check is file exist.So your code should be something like:
http://qt-project.org/doc/qt-5/qfile.html#exists-2