Qt的XML文件读取测试01
用Qt读取XML文件中的配置并且进行打印。
主函数main.cpp进行模拟,DataManager进行数据读取,具体实现如下:
Pro文件
QT -= gui
QT += xml
CONFIG += c++11 console
CONFIG -= app_bundle
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
DataManager.cpp \
main.cpp
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
HEADERS += \
DataManager.h
需要再Qt中配置xml选项。
DataManager
#ifndef DATAMANAGER_H
#define DATAMANAGER_H
#include <QObject>
#include <QFile>
#include <QDir>
#include <QFile>
#include <QTextStream>
#include <QDomDocument>
#include <QXmlStreamWriter>
#include <QDebug>
class DataManager: public QObject
{
Q_OBJECT
public:
explicit DataManager(QObject *parent = nullptr);
void analyse(const QString& filename);
private:
QString m_Address;
QString m_Version;
};
#endif // DATAMANAGER_H
analyse()用来解析XML文件。
#include "DataManager.h"
DataManager::DataManager(QObject *parent)
{
}
void DataManager::analyse(const QString &filename)
{
QFile file(filename);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "文件打开失败!";
return;
}
QXmlStreamReader stream_reader;
stream_reader.setDevice(&file);
while(!stream_reader.atEnd()) {
QXmlStreamReader::TokenType node = stream_reader.readNext();
if(node == QXmlStreamReader::StartElement) {
QString element = stream_reader.name().toString();
if(element == "HOST_ADDRESS") {
node = stream_reader.readNext();
if(node == QXmlStreamReader::Characters) {
QString host_address = stream_reader.text().toString();
qDebug() << "Host: " << host_address;
}
} else if(element == "PORT") {
node = stream_reader.readNext();
if(node == QXmlStreamReader::Characters) {
int port = stream_reader.text().toInt();
qDebug() << "Port: " << QString::number(port);
}
}
}
}
if(stream_reader.hasError()){
return;
}
file.close();
}
假设只配置了地址和端口号,解析读取并打印。
XML内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<HOST_ADDRESS>127.0.0.1</HOST_ADDRESS>
<PORT>8849</PORT>
</root>
这个XML文件需要放到代码路径下。
主函数
#include <QCoreApplication>
#include <QDebug>
#include "DataManager.h"
int main(int argc, char *argv[])
{
DataManager manager;
QString filename = "./Config.xml";
manager.analyse(filename);
qDebug() << "Finished!";
return 0;
}
执行结果如下:
解析完毕。