Qt通过dom方式修改xml

1.jpg

[代码] 修改属性值

  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. }
[代码] 修改节点值
  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. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值