You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Qt C++解析含注释XML时QDomNode为null如何跳过注释读取Info标签

问题原因

  • QDomNode包含多种节点类型,你遇到的null节点实际是注释节点(QDomNode::CommentNode)和XML元素之间的空白文本节点(QDomNode::TextNode),这两类节点调用toElement()都会返回空的QDomElement
  • 原有代码逻辑错误:调用Identity.nextSibling().toElement()后没有重新赋值给Identity变量,相当于没执行跳过操作
  • 标签名匹配错误:你的XML中节点名是Info,但代码里判断的是Identity,永远匹配失败

修正后的实现代码

QDomDocument xmldoc;
QFile file("./Manifest.xml");

if (!file.open(QIODevice::ReadOnly)){
    qDebug() << "Failed to open file";
    return;
}

// 增加setContent返回值判断,避免XML格式错误导致后续异常
if (!xmldoc.setContent(&file)) {
    qDebug() << "XML format error";
    file.close();
    return;
}
file.close();

QDomElement root = xmldoc.documentElement();
QDomNode currentNode = root.firstChild();
QDomElement infoElement;

// 遍历所有子节点,跳过非元素节点
while (!currentNode.isNull()) {
    // 仅处理Element类型的有效节点
    if (currentNode.isElement()) {
        QDomElement elem = currentNode.toElement();
        if (elem.tagName() == "Info") {
            infoElement = elem;
            break;
        }
    }
    currentNode = currentNode.nextSibling();
}

if (!infoElement.isNull()) {
    QString currver = infoElement.attribute("Version", "Unknown");
    QString name = infoElement.attribute("Name", "Unknown");
    QString arch = infoElement.attribute("ProcessorArchitecture", "Unknown");
    qDebug() << "Version:" << currver << "Name:" << name << "Arch:" << arch;
} else {
    qDebug() << "Fail: Info tag not found";
}

可选简化方案

如果仅需要快速定位Info标签,不需要逐个遍历子节点,可以直接用elementsByTagName方法快速匹配:

QDomNodeList infoList = root.elementsByTagName("Info");
if (!infoList.isEmpty()) {
    QDomElement infoElement = infoList.at(0).toElement();
    QString currver = infoElement.attribute("Version", "Unknown");
    qDebug() << currver;
} else {
    qDebug() << "Info tag not found";
}

内容的提问来源于stack exchange,提问作者BananaBlu77

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 08:24:02