zoukankan      html  css  js  c++  java
  • Qt 操作QDomDocument对象修改节点

     

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
    本文链接:https://blog.csdn.net/liulihuo_gyh/article/details/41321369

    代码部分:

    QFile file(filePath);

    if (!file.open(QFile::ReadOnly | QFile::Text)) 
    {
    QMessageBox::critical(NULL,tr("错误"),tr("无法打开%1文件").arg(filePath),QMessageBox::Ok);
    return;
    }
    QString error;
    int row = 0;
    int col= 0 ;
    QDomDocument dom;
    if (!dom.setContent(&file, false, &error, &row, &col))
    {
    QMessageBox::warning(0, tr("error"), tr("错误%1, 行%2, 列%3").arg(error).arg(row).arg(col), QMessageBox::Yes);
    file.close();
    return;
    }

    QDomElement root = dom.documentElement();// 根节点
    QDomNodeList nlist = root.elementsByTagName("tag"); //要修改的tag
    for (int i=0; i<nlist.count(); i++)
    {

    QDomElement ele = nlist.at(i).toElement();

    //关键1

    QDomNode oldNode = ele.firstChild(); //旧节点
    ele.firstChild().setNodeValue(QString::number(channel)); //改值
    QDomNode newNode = ele.firstChild(); //新节点
    ele.replaceChild(newNode, oldNode); //替换
    }

    file.close();

    //关键2

    QFile wfile(filePath);
    if (!wfile.open(QIODevice::WriteOnly))
    {
    QMessageBox::critical(NULL,tr("错误"),tr("无法打开%1文件").arg(filePath),QMessageBox::Ok);
    return;
    }
    QTextStream out(&wfile);
    QString save = dom.toString();
    out << dom.toString();

    wfile.close();

    用一个dom对象,两个文件对象, 一个读打开修改,令一个重写, 直接修改不成功.

  • 相关阅读:
    安装IDEA
    缓存工具CacheUtil
    使用Eclipse上传/下载Git项目
    Sublime文本排序&查找重复行&删除重复行
    Sublime Text 3 配置Java开发
    安装XMind
    安装Maven
    安装MySQL
    安装Eclipse及相关Plugin
    Android Xposed框架中创建模块的指导手册
  • 原文地址:https://www.cnblogs.com/lvdongjie/p/11786084.html
Copyright © 2011-2022 走看看