Qt按层级解析xml文件内容
在Qt中,可以使用QDomDocument类来解析XML文件内容。以下是一个按层级解析XML文件内容的示例代码:
#include <QFile>
#include <QDebug>
#include <QtXml>
void parseNode(const QDomNode& node, int indentLevel)
{
QDomNode domNode = node.firstChild();
while (!domNode.isNull()) {
if (domNode.isElement()) {
QDomElement element = domNode.toElement();
QString tagName = element.tagName();
// 缩进输出
for (int i = 0; i < indentLevel; i++) {
qDebug() << " ";
}
qDebug() << "Tag Name:" << tagName;
// 解析属性
QDomNamedNodeMap attributes = element.attributes();
for (int i = 0; i < attributes.count(); i++) {
QDomNode attribute = attributes.item(i);
QString attributeName = attribute.nodeName();
QString attributeValue = attribute.nodeValue();
// 缩进输出
for (int j = 0; j < indentLevel + 2; j++) {
qDebug() << " ";
}
qDebug() << "Attribute Name:" << attributeName << "Value:" << attributeValue;
}
// 解析子节点
parseNode(element, indentLevel + 2);
}
domNode = domNode.nextSibling();
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile file("example.xml");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "Failed to open the file.";
return -1;
}
QDomDocument document;
if (!document.setContent(&file)) {
qDebug() << "Failed to parse the file.";
file.close();
return -1;
}
file.close();
QDomElement root = document.documentElement();
parseNode(root, 0);
return a.exec();
}
在上面的代码中,首先使用QFile类打开XML文件,然后使用QDomDocument类的setContent()函数将文件内容读取到QDomDocument对象中。接下来,通过调用document.documentElement()函数获取根节点,并调用parseNode()函数解析根节点及其子节点的内容。parseNode()函数使用递归的方式遍历所有的节点,输出节点的标签名、属性以及子节点
原文地址: https://www.cveoy.top/t/topic/h0M5 著作权归作者所有。请勿转载和采集!