Qt 遍历 xml

遍历xml(打印节点名和属性)

【核心方法】

void traverseNode(QDomElement e) {
    QDomNamedNodeMap attrs = e.attributes();
    qDebug() << e.nodeName() << e.text();

    // 遍历属性
    for (int i = 0; i < attrs.count(); i++)
    {
        QDomNode attr =  attrs.item(i);
        if (!attr.isNull() && attr.isAttr()) {
            qDebug() << "-" << attr.nodeName() << attr.nodeValue();
        }
    }
    
    // 遍历子节点
    QDomNode child = e.firstChild();
    while (!child.isNull() && child.isElement())
    {
        QDomElement childele = child.toElement(); // try to convert the node to an element.
        traverseNode(childele);
        child = child.nextSibling();
    }
}

【调用】

QFile file("/Users/zdy/Desktop/My.xml");
QDomDocument document;
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
    qDebug() << "Failed to open file";
    return;
}
else
{
    if (!document.setContent(&file))
    {
        qDebug() << "Failed to open document";
        return;
    }
    file.close();
}
QDomElement root = document.documentElement();
traverseNode(root);
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,958评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,766评论 18 399
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,403评论 25 708
  • 系统中的各个服务有的是IO密集型,有的是CPU密集型,内存密集型不同的系统性能的瓶颈不同,比如说:如果数据库成为瓶...
    美得冒泡的姗迪阅读 1,517评论 0 0
  • 1.为什么搜索是iOS 9的杀手级特性? 当用户升级到iOS 9系统了以后,出现了下面的使用场景: 用户手机上Ap...
    牛哥小小阅读 413评论 1 2