PDA

View Full Version : creating Xml file using QT



rk0747
29th January 2010, 13:18
hi ,
i have created an xml file using iostream in Qt , but i come to know we have to use xml Dom for manipulations like save, open,update and delete in the xml file .
i read the xml dom concept in C++ programming QT , but i didn't understand clearly how to create and read an xml domdocument, i am attaching xml file what i was created , please suggest me how to do this?

Thankyou

pitonyak
29th January 2010, 16:16
Reading is easy (this example, I should probably close the file.... oops)

QString filename = "C:/test.xml";
QFile file(filename);
if (!file.open(QFile::ReadOnly | QFile::Text))
{
qDebug(qPrintable(QString("Error: Cannot read file %1 %2").arg(filename).arg(file.errorString())));
return;
}
QDomDocument doc;
doc.setContent(&file);

Is your real concern related to processing? Consider this small example that traverses a DOM tree

void pp(QTextStream& os, QDomNode node)
{
while (!node.isNull())
{
if (node.isElement())
{
// Ignore attributes for now.
//qDebug(qPrintable(QString("DEBUG: <%1>").arg(node.toElement().tagName())));
os << "<" << node.toElement().tagName() << ">";
if (node.hasChildNodes())
{
QDomNode childNode = node.firstChild();
pp(os, childNode);
}
// Print all children
//qDebug(qPrintable(QString("DEBUG: </%1>").arg(node.toElement().tagName())));
os << "</" << node.toElement().tagName() << ">";
}
else if (node.isText())
{
os << node.toText().data();
}
else
{
qDebug(qPrintable(QString("Unexpected node type:")));
//qDebug(qPrintable(QString("Unexpected node type: %1").arg((int)(node.NodeType()))));
}
node = node.nextSibling();
}
}
The example ignores attributes. The head node that I would pass as an argument is found using doc.documentElement().
This snippet copies a node out of a DOM tree and removes the node. I then insert the node in a different location.

QString xmlOriginal = "<xml><item><a>1</a></item><item><a>2</a></item></xml>";
QDomDocument doc;
doc.setContent(xmlOriginal);
QDomElement docElement = doc.documentElement();
QDomNode firstChild = docElement.firstChild();
QDomNode secondChild = firstChild.nextSibling();
QDomNode clonedNode = secondChild.cloneNode(true);
doc.documentElement().removeChild(secondChild);
doc.documentElement().insertBefore(clonedNode, firstChild);
QString s2;
QTextStream os2(&s2);
os2 << "\nStream *****\n" << doc;
qDebug(qPrintable(s2));

aamer4yu
30th January 2010, 06:02
Please dont start another thread for same topic [Original Post (http://www.qtcentre.org/threads/27619-update-the-xml-file-from-QT-program?p=130972&highlight=#post130972) ]

mkkguru
30th January 2010, 11:16
Please go through the basics from QtAssistant,all the best