Qt之读(解析)XML文件
扫描二维码
随时随地手机看文章
先上代码
//从config.xml中获取标签appenvironment和oa_app_version的值
//appenvironment值为pro表示生产,为pre表示预生产
QMap readXml()
{
QMap mapList;
mapList.clear();
QString configXMLPath = QCoreApplication::applicationDirPath()+"\config\config.xml";
QFile file(configXMLPath);
if (file.open(QIODevice::ReadOnly | QIODevice::Text))
{
QXmlStreamReader reader(&file);
while (!reader.atEnd() && !reader.hasError())
{
QXmlStreamReader::TokenType token = reader.readNext();
if (token == QXmlStreamReader::StartElement)
{
if (reader.name() == "appenvironment" || reader.name() == "oa_app_version")
{
QXmlStreamAttributes attributes = reader.attributes();
if (attributes.hasAttribute("value"))
{
QString strValue = attributes.value("value").toString();
mapList.insert(reader.name().toString(), strValue);
}
}
}
}
//解析出错
if (reader.hasError())
{
QString errorInfo = QStringLiteral("XML解析错误:%1 行号:%2 列号:%3 字符位移:%4").
arg(reader.errorString()).arg(reader.lineNumber()).arg(reader.columnNumber()).arg(reader.characterOffset());
qDebug() << errorInfo;
}
file.close();
reader.clear();
}
return mapList;
}
这样写,如果是QApplication a(argc, argv);之后调用QMap此时可以调用Windows API,如下所示。
//从config.xml中获取标签appenvironment和oa_app_version的值
//appenvironment值为pro表示生产,为pre表示预生产
QMap readXml()
{
QMap mapList;
mapList.clear();
TCHAR szPath[MAX_PATH] = { 0 };
GetModuleFileName(NULL, szPath, MAX_PATH);
(_tcsrchr(szPath, _T('\')))[1] = 0;
QString configXMLPath= QString::fromUtf16((const ushort *)szPath)+"config\config.xml";
QFile file(configXMLPath);
if (file.open(QIODevice::ReadOnly | QIODevice::Text))
{
QXmlStreamReader reader(&file);
while (!reader.atEnd() && !reader.hasError())
{
QXmlStreamReader::TokenType token = reader.readNext();
if (token == QXmlStreamReader::StartElement)
{
if (reader.name() == "appenvironment" || reader.name() == "oa_app_version")
{
QXmlStreamAttributes attributes = reader.attributes();
if (attributes.hasAttribute("value"))
{
QString strValue = attributes.value("value").toString();
mapList.insert(reader.name().toString(), strValue);
}
}
}
}
//解析出错
if (reader.hasError())
{
QString errorInfo = QStringLiteral("XML解析错误:%1 行号:%2 列号:%3 字符位移:%4").
arg(reader.errorString()).arg(reader.lineNumber()).arg(reader.columnNumber()).arg(reader.characterOffset());
qDebug() << errorInfo;
}
file.close();
reader.clear();
}
return mapList;
}
XML格式如下。