我有一个Xml文件:
<?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>
我需要检查root元素是否&#34; AutoSaveSettings&#34;使用qt c ++存在于xml中。如果根元素存在,则删除自动保存设置之前和之后的注释行?我们怎么能在qt c ++中做到这一点。如何在c ++中执行此操作。检查是否存在start元素或根元素
#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();
}
答案 0 :(得分:1)
尝试这样的事情:
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;
}
编辑:另一种方法可能是使用QDomDocument
没有重新编目,因为QDomDocument不再被主动维护
bool elementExists( QFile & file,const QString & elementName){
QDomDocument reader;
reader.setContent(&file, true);
QDomNodeList elementList = reader.elementsByTagName(elementName);
return elementList.size()>0;
}