PDA

View Full Version : How to read a xml file in qt?



Gokulnathvc
11th January 2012, 09:42
Help me in giving a sample or simple application on how to read the contents of the xml file in QT
?

wysota
11th January 2012, 10:17
int main() {
QFile file("file.xml");
file.open(QIODevice::ReadOnly|QIODevice::Text);
QDomDocument doc;
doc.setContent(&file);
return 0;
}

Gokulnathvc
11th January 2012, 10:32
It says QDomDocument has incomplete type name.

wysota
11th January 2012, 10:37
Too bad. After writing over 200 posts you should know how to include header files and enable Qt modules.

Gokulnathvc
11th January 2012, 10:50
I have added header file and class. still it says this error

Zlatomir
11th January 2012, 14:25
Also include the QDomNode and QDomElement (not sure if this is the issue, but you will probably use that classes) and don't forget to add QT += xml in the .pro file (then rebuild).

Gokulnathvc
17th January 2012, 11:35
The following code works fine.


QFile* file = new QFile("C:\\persons.xml");
QFile txtfile("xmldata.txt");

/* If we can't open it, let's show an error message. */
if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) {
QMessageBox::critical(this,
"QXSRExample::parseXML",
"Couldn't open example.xml",
QMessageBox::Ok);
return;
}
/* QXmlStreamReader takes any QIODevice. */
QXmlStreamReader xml(file);
while (!xml.atEnd() && !xml.hasError())
{
xml.readNext();
if (xml.isStartElement())
{
QString name = xml.name().toString();
if (name == "firstname" || name == "surname" ||
name == "email" || name == "website")
{
txtfile.open(QIODevice::WriteOnly | QIODevice::Text);
txtfile.write("Element Name:");
txtfile.write("\r\n");
txtfile.write(name.toStdString().c_str());
txtfile.write("\r\n");
txtfile.write("Text:");
txtfile.write("\r\n");
txtfile.write(xml.readElementText().toStdString(). c_str());
txtfile.write("\r\n");
}
}
}
if (xml.hasError())
{
QMessageBox::warning(NULL,"Error",xml.errorString(),QMessageBox::Ok);
}
else if (xml.atEnd())
{
QMessageBox::warning(NULL,"End","Reached End!!!",QMessageBox::Ok);
}

txtfile.close();
file->close();


XML file is

<?xml version="1.0" encoding="iso-8859-1" ?>
<persons>
<person>
<firstname>John</firstname>
<surname>Doe</surname>
<email>john.doe@example.com</email>
<website>http://en.wikipedia.org/wiki/John_Doe</website>
</person>
<person>
<firstname>Jane</firstname>
<surname>Doe</surname>
<email>jane.doe@example.com</email>
<website>http://en.wikipedia.org/wiki/John_Doe</website>
</person>
<person>
<firstname>Matti</firstname>
<surname>Meikäläinen</surname>
<email>matti.meikalainen@example.com</email>
<website>http://fi.wikipedia.org/wiki/Matti_Meikäläinen</website>
</person>
</persons>