免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4283 | 回复: 1
打印 上一主题 下一主题

Qt通过dom方式修改xml [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-02-12 11:55 |只看该作者 |倒序浏览


[代码] 修改属性值
  1. bool QXmlEdit::SetAValue(const QString &key, const QVariant &value)
  2. {
  3.     try
  4.     {
  5.         QString tag;
  6.         QString attName;
  7.         QStringList sl=key.split("/");
  8.         tag = sl.at(0);
  9.         attName = sl.at(1);

  10.         QDomElement docElem = doc.documentElement();
  11.         QDomNodeList nodeList = docElem.elementsByTagName(tag);
  12.         if (nodeList.count() >0 )
  13.         {
  14.             QDomElement el = nodeList.at(0).toElement();
  15.             el.setAttribute(attName,value.toString());  //设置属性值

  16.             QFile file(fileName);
  17.             if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
  18.             {
  19.                 return false;
  20.             }
  21.             QTextStream out(&file);
  22.             doc.save(out,4);
  23.         }
  24.         return true;
  25.     }
  26.     catch (...)
  27.     {
  28.         return false;
  29.     }
  30. }
复制代码

论坛徽章:
0
2 [报告]
发表于 2011-02-12 11:56 |只看该作者
[代码] 修改节点值
  1. bool QXmlEdit::SetTValue(const QString &key, const QVariant &value)
  2. {
  3.     try
  4.     {
  5.         QDomElement docElem = doc.documentElement();
  6.         QDomNodeList nodeList = docElem.elementsByTagName(key);
  7.         if (nodeList.count() >0 )
  8.         {
  9.             QDomElement el = nodeList.at(0).toElement();  //tag为key的节点
  10.             QDomNode oldnode = el.firstChild();           //标签之间的内容作为节点的子节点出现,得到原来的子节点
  11.             el.firstChild().setNodeValue(value.toString());   //用提供的value值来设置子节点的内容

  12.             QDomNode newnode = el.firstChild();               //值修改过后的子节点

  13.             el.replaceChild(newnode,oldnode);                 //调用节点的replaceChild方法实现修改功能
  14.         
  15.             QFile file(fileName);
  16.             if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
  17.             {
  18.                 return false;
  19.             }
  20.             QTextStream out(&file);
  21.             doc.save(out,4);
  22.         }
  23.         return true;
  24.     }
  25.     catch (...)
  26.     {
  27.         return false;
  28.     }
  29. }
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP