在 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() 函数使用递归的方式遍历所有的节点,输出节点的标签名、属性以及子节点。

Qt XML 解析:层级解析 XML 文件内容

原文地址: https://www.cveoy.top/t/topic/pJQH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录