test.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<Startaniminal="cat">
<book>book1</book>
</Start>
simpleWriter.cpp
#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
<Startaniminal="cat">
<book>book1</book>
</Start>
dom.cpp
#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不影响效率