test.xml

Xml代码
  1. <?xmlversion="1.0"encoding="UTF-8"?>

  2. <Startaniminal="cat">

  3. <book>book1</book>

  4. </Start>



simpleWriter.cpp

C++代码
#include
#include
#include
using namespace std;void writeXML(){ QFile file("test.xml"); if(not file.open(QIODevice::ReadWrite)) return; QXmlStreamWriter writer(&file); writer.setAutoFormatting(true); writer.writeStartDocument(); writer.writeStartElement("Start"); writer.writeAttribute("animinal","cat"); writer.writeTextElement("book","book1"); writer.writeEndElement();//Start writer.writeEndDocument(); file.close();}int main(){ writeXML();}



dom读写
dom.xml

Xml代码
  1. <Startaniminal="cat">

  2. <book>book1</book>

  3. </Start>



dom.cpp

C++代码
#include
#include
#include
#include
#include
using namespace std;void writeDom(){ QFile file("dom.xml"); if(not file.open(QIODevice::ReadWrite)) return; QDomDocument doc; QDomElement startElem = doc.createElement("Start"); doc.appendChild(startElem); startElem.setAttribute("animinal","cat"); QDomElement bookElem = doc.createElement("book"); bookElem.appendChild(doc.createTextNode("book1")); startElem.appendChild(bookElem); QTextStream out(&file); doc.save(out,3); file.close();}void readDom(){ QFile file("dom.xml"); if(not file.open(QIODevice::ReadWrite)) return; QDomDocument doc; doc.setContent(&file); QDomElement startElem = doc.documentElement(); cout << "animainal:"; cout << startElem.attribute("animinal").toStdString() << endl; cout << "book:"; cout << startElem.firstChildElement("book").text().toStdString() << endl; file.close();}int main(){ writeDom(); readDom();}



sax读写,就不贴代码了,一般情况下,3,5000行的xml用dom不影响效率