Qt读写xml文件


写xml

<root>
    <element>
        <sub id=-1></sub>
    </element>
</root>

//添加xml说明
  QDomDocument doc;
  QDomProcessingInstruction instru;
  instru = doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
  doc.appendChild(instru);
//添加根节点
  QDomElement root = doc.createElement("root");
  doc.appendChild(root);
  root.setAttribute("ver", "1.0.0");
 //添加元素
  QDomElement elementNode= doc.createElement(" element");
  QDomElement subNode= doc.createElement("sub");
  subNode.setAttribute("id", "-1");
  
  elementNode.appendChild(subNode);
  root.appendChild(elementNode);
//写文件
  QFile file(fileName);
  file.open(QIODevice::WriteOnly | QIODevice::Truncate);
  QTextStream out(&file);
  doc.save(out, 4);
  file.close();
}

  读xml

QDomDocument doc;
//读取xml文件到QDomDocument 对象中
  QFile file(fileName);
  if (!file.open(QIODevice::ReadOnly)) return false;
  if (!doc.setContent(&file)){
    file.close();
    return false;
  }
  file.close();
//找到对应节点
  QDomElement rootEle = doc.documentElement();
  if ("root" != rootEle.nodeName()) return false;
  if ("1.0.0" != rootEle.attribute("ver")) return false;
  
  QDomNodeList subList= doc.elementsByTagName("sub");
  for (int index = 0; index != subList.size(); ++index){
    QDomNode node = subList.at(index);
    if (!node.isElement()) continue;
    QDomElement subEle= node.toElement();
    
    QString id= subEle.attribute("id");
  }

  已经工作的程序员朋友可以关注下我的gzh“程序员成长日志”,分享日常工作中解决的问题即可赚取稿费,大家一起成长~

猜你喜欢

转载自www.cnblogs.com/czrz1024/p/12675857.html