[SOLVED] Opening XML files
-
Hi!
I'm currently creating a simple game using Qt and I want to have a highscores feature in my game. For that I was going to use an XML file, but I'm having problems with the code. My code looks like this:
QFile highscores(":/statistics/resources/highscores.xml"); if(highscores.exists())qDebug() << "File exists"; QDomDocument document; QDomElement root = document.createElement("Ranks"); document.appendChild(root); for(int i = 0; i < 10; i++) { QDomElement entry = document.createElement("Entry"); entry.setAttribute("Name", ""); entry.setAttribute("Rank", QString::number(i+1)); entry.setAttribute("Score",QString::number(0)); root.appendChild(entry); } if(!highscores.open(QIODevice::WriteOnly | QIODevice::Text)) { qDebug() << "Failed to open file for writing"; } else { QTextStream stream(&highscores); stream << document.toString(); highscores.close(); qDebug() << "Finished"; }
When I run the program the output is
"File exists"
"Failed to open file for writing"Can anyone explain why I can't seem to open the file?
cheers,
Jon -
@JonBriem said:
QFile highscores(":/statistics/resources/highscores.xml"); if(!highscores.open(QIODevice::WriteOnly | QIODevice::Text)) { qDebug() << "Failed to open file for writing"; }
is that path inside the resource file? (which is linked into the exe)
changing the path to
QFile highscores ( "highscores.xml" );
the code below did produce the expected xml file.QDomDocument document; void CreateRanks() { QDomElement root = document.createElement ( "Ranks" ); document.appendChild ( root ); for ( int i = 0; i < 10; i++ ) { QDomElement entry = document.createElement ( "Entry" ); entry.setAttribute ( "Name", "" ); entry.setAttribute ( "Rank", QString::number ( i + 1 ) ); entry.setAttribute ( "Score", QString::number ( 0 ) ); root.appendChild ( entry ); } } void SaveRanks() { QFile highscores ( "highscores.xml" ); if ( !highscores.open ( QIODevice::WriteOnly | QIODevice::Text ) ) { qDebug() << "Failed to open file for writing"; } else { QTextStream stream ( &highscores ); stream << document.toString(); highscores.close(); qDebug() << "Finished"; } } int main ( int argc, char* argv[] ) { CreateRanks(); SaveRanks(); }