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");
  }

原文來自微信公眾號"程序員成長日志",已經工作的程序員朋友可以關注下公眾號“程序員成長日志”,分享日常工作中解決的問題即可賺取稿費,大家一起成長~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM