cyley
cyley

Reputation: 73

Checking if root element exist in Xml using qt c++

I have an Xml file:

 <?xml version="1.0" encoding="utf-8" ?>
 <AppConfig>
 <DefaultCulture></DefaultCulture>
 <StartupMessageTitle></StartupMessageTitle>
 <StartupMessageText></StartupMessageText>
 <StartupMessageIcon>Information</StartupMessageIcon>
 <DefaultProfileSettings>
 <DriverName>wia</DriverName>
 <UseNativeUI>false</UseNativeUI>
 <IconID>0</IconID>
 <MaxQuality>false</MaxQuality>
 <AfterScanScale>OneToOne</AfterScanScale>
 <Brightness>0</Brightness>
 <Contrast>0</Contrast>
 <BitDepth>C24Bit</BitDepth>
 <PageAlign>Left</PageAlign>
 <PageSize>Letter</PageSize>
 <Resolution>Dpi100</Resolution>
 <PaperSource>Glass</PaperSource>
 </DefaultProfileSettings>
 <!--
 <AutoSaveSettings>
 <FilePath></FilePath>
 <ClearImagesAfterSaving>false</ClearImagesAfterSaving>
 <Separator>FilePerPage</Separator>
 </AutoSaveSettings>
  -->
 </AppConfig>

I need to check if root elements "AutoSaveSettings" exists in xml using qt c++ . if the root elements exists then remove the commented line before and after the Auto save settings? How can we do it in qt c++. How do I perform this operation in c++.Check if exists start element or root element

  #include <QtCore>
  #include <QtXml/QDomDocument>
  #include <QDebug>
  #include <QFile>
  #include <QXmlStreamReader>

  bool elementExists(const QFile &file, const QString &elementName)      
  {

     QXmlStreamReader reader(&file);

     while (reader.readNextStartElement())
      {
        if(reader.name() == elementName)
         {
           return true;
         }
     }
     return false;
   }

  int main(int argc,char *argv[])
   {
     QCoreApplication a(argc,argv);

     QDomDocument document;
     QFile file = "C:/Program Files (x86)/NAPS2/appsettings.xml";
     if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
     {
         qDebug()<<"Failed to open the file";
         return -1;
     }
     else{
         if(!document.setContent(&file))
         {
             qDebug()<< "Failed to load Document";
             return -1;
         }
         file.close();
     }

     elementExists(file,"AutoSaveSettings");

     qDebug()<< "Finished";

     return a.exec();
    }

Upvotes: 2

Views: 1376

Answers (1)

Venom
Venom

Reputation: 1060

Try something like this :

bool elementExists( QFile & file, const QString & elementName){

    QXmlStreamReader reader (&file);

    while (reader.readNextStartElement()){
        if(reader.name() == elementName) return true; 
       //elementName should be "AutoSaveSettings"
    }
    return false;
}

Edit : an alternative way could be using QDomDocument

Not recomanded because QDomDocument is not actively maintained anymore

bool elementExists( QFile & file,const QString & elementName){

    QDomDocument reader;
    reader.setContent(&file, true);
    QDomNodeList elementList =  reader.elementsByTagName(elementName);
    return elementList.size()>0;
}

Upvotes: 1

Related Questions