In Qt, we sometimes need to write some parameters to the XML file, so that we can read it later, like an archive read operation, for example, we want to generate the following XML file:
<?XML version= "1.0" encoding= "UTF-8"?><Parameters> <para1>1</para1> <Para2>2</Para2> <Para3>3</Para3></Parameters>
The write operation is described in the following code:
voidqtmainwindow::on_actionsave_triggered () {QString filename= Qfiledialog::getsavefilename ( This, TR ("Save Xml"),".", TR ("Xml Files (*.xml)")); QFile file (filename); File.Open (qiodevice::writeonly); Qxmlstreamwriter XmlWriter (&file); Xmlwriter.setautoformatting (true); Xmlwriter.writestartdocument (); Xmlwriter.writestartelement ("Parameters"); Xmlwriter.writetextelement ("para1", Qstring::number (1)); Xmlwriter.writetextelement ("Para2", Qstring::number (2)); Xmlwriter.writetextelement ("Para3", Qstring::number (3)); Xmlwriter.writeendelement (); Xmlwriter.writeenddocument (); File.close ();}
Read-in operations see the following:
voidqtmainwindow::on_actionload_triggered () {QString filename= Qfiledialog::getopenfilename ( This, TR ("Open Xml"),".", TR ("Xml Files (*.xml)")); QFile file (filename); if(!file.open (Qfile::readonly |Qfile::text)) {Std::cerr<<"Error:cannot Read File"<<qprintable (filename)<<": "<<qprintable (file.errorstring ())<<Std::endl; } Qxmlstreamreader XmlReader (&file); Xmlreader.readnext (); while(!Xmlreader.atend ()) { if(Xmlreader.isstartelement ()) {if(Xmlreader.name () = ="Parameters") {xmlreader.readnext (); } Else if(Xmlreader.name () = ="para1") { intPARA1 =Xmlreader.readelementtext (). ToInt (); Xmlreader.readnext (); } Else if(Xmlreader.name () = ="Prefiltercap") { intPara2 =Xmlreader.readelementtext (). ToInt (); Xmlreader.readnext (); } Else if(Xmlreader.name () = ="sadwindowsize") { intPARA3 =Xmlreader.readelementtext (). ToInt (); Xmlreader.readnext (); } Else{xmlreader.raiseerror (Qobject::tr ("Not a options file")); } } Else{xmlreader.readnext (); } file.close (); if(Xmlreader.haserror ()) {Std::cerr<<"error:failed to parse file"<< qprintable (filename) <<": "<< qprintable (xmlreader.errorstring ()) <<Std::endl; } Else if(File.error ()! =qfile::noerror) {Std::cerr<<"Error:cannot Read File"<<qprintable (filename)<<": "<<qprintable (file.errorstring ())<<Std::endl; } }}
Qt write and read XML file read and write XML files