【发布时间】:2017-03-27 07:15:40
【问题描述】:
我有一个 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>
我需要使用 qt c++ 检查 xml 中是否存在根元素“AutoSaveSettings”。如果根元素存在,那么在自动保存设置之前和之后删除注释行?我们如何在 qt c++ 中做到这一点。如何在 C++ 中执行此操作。检查是否存在起始元素或根元素
#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();
}
【问题讨论】:
-
你试过使用 QXmlStreamReader 吗?因为我可以看到有一个方法 bool isComment() const;抱歉,我不会将代码作为答案,因为我不确定 QXmlStreamReader 是否可以正常工作。您可以在文档doc.qt.io/qt-5/qxmlstreamreader.html 中查看示例
-
首先我需要确定“AutoSaveSettings”是否存在?我该怎么做
-
DOM Parser 可能更容易使用。基本思路:枚举每个子节点,检查是否为
QDomComment,使用QDomComment::data()获取评论字符串。使用this method 将字符串转换为QDomElement并在文档中的适当位置插入新元素。 -
首先我需要找出 If "AutoSaveSettings" - 你必须枚举所有节点并检查它是否是评论节点,然后比较字符串内容。评论只是字符串,直接找不到。
-
我发布了一些代码。告诉我它是否有效