#include <QCoreApplication>
#include <QDomDocument>
#include <QFile>
#include <iostream>
#include <QDebug>
using namespace std;
void xmlFile()
{
QDomDocument doc("mydocument");
QFile file("mydocument.xml");
if (!file.open(QIODevice::ReadOnly))
return;
if (!doc.setContent(&file)) {
file.close();
return;
}
file.close();
// print out the element names of all elements that are direct children
// of the outermost element.
QDomElement docElem = doc.documentElement();
QDomNode n = docElem.firstChild();
while(!n.isNull()) {
QDomElement e = n.toElement(); // try to convert the node to an element.
if(!e.isNull())
{
cout << e.tagName().toStdString() << "-->" << e.text().toStdString() << endl; // the node really is an element.
if(e.hasAttributes())
{
std::cout << qPrintable(e.attribute("href","href")) << "-->" << qPrintable(e.attribute("name","name")) << std::endl;
}
}
n = n.nextSibling();
}
// Here we append a new element to the end of the document
QDomElement elem = doc.createElement("img");
elem.setAttribute("src", "myimage.png");
docElem.appendChild(elem);
{
QFile file("mydocument.xml");
if (!file.open(QIODevice::WriteOnly|QIODevice::Truncate))
return;
file.write(doc.toString().toStdString().c_str(),doc.toString().toStdString().size());
file.close();
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
xmlFile();
return a.exec();
}
#-------------------------------------------------
#
# Project created by QtCreator 2015-10-21T14:05:35
#
#-------------------------------------------------
QT += core xml
QT -= gui
TARGET = qt_xml
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp
<note>
<to href="demo.asp" name="星星">George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>