PDA

View Full Version : XML parse



arunredi
26th April 2008, 13:16
Hello,

I'm trying to read all the values of a particular tag (in this case 'name') with in the xml file.
below is the actual xml file:


<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<response>
<status>ok</status>
<project_list>
<project>
<id>1911</id>
<url>http://www.snipitron.com/arun/Qt_code</url>
<name>Qt code</name>
</project>
<project>
<id>1902</id>
<url>http://www.snipitron.com/arun/Mac_app</url>
<name>Mac app</name>
</project>
</project_list>
</response>

And i'm having the Qt code to read the name value as below:


if (docElement.tagName() == "response"){
stat = docElement.firstChildElement("status").text();
statMsg = docElement.firstChildElement("message").text();
if (stat == "ok" ){
projNameNode = docElement.elementsByTagName("name");
for (uint j = 0; j < projNameNode.count(); j++)
{
nodeMsg = projNameNode.item(j).toElement().attribute("name");
QMessageBox::critical(this, "Arun", nodeMsg, QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton);

}

}
} else
QMessageBox::critical(this, "Arun", "Status: " + stat + " Message: " + statMsg, QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton);
}

I'm missing something here and hence i'm getting NULL as value for nodeMsg.

any help is greatly appreciated.

thanks,
Ar

patrik08
26th April 2008, 13:39
You must only iterate xml document ... this here is a rss sample ...

if you have qt4.4 learn http://doc.trolltech.com/4.4rc1/qxmlquery.html QXmlQuery
and make a query like a database...




typedef QMap<int, QStringList> RssParams;

/* read a static rss version 1/2 file and return QMap params of link title description */
RssParams ReadRssFile( QString fileplace , int limiter )
{
RssParams contingent;
QFile xmlfile( fileplace );
QString errorStr, obname, inhalt;
int errorLine, errorColumn, position;
position = 0 -1;
QDomDocument doc("RSS");
if(!xmlfile.open( QIODevice::ReadOnly ) ) {
return contingent;
}
if (!doc.setContent(&xmlfile,true, &errorStr, &errorLine, &errorColumn)) {
xmlfile.close();
return contingent;
}
QDomElement root = doc.documentElement();
QDomElement chanelbase = root.firstChildElement("channel");
QDomElement child = chanelbase.firstChildElement("item");
while (!child.isNull()) {
QString title = child.firstChildElement("title").text();
QString desc = child.firstChildElement("description").text();
QString urirss = child.firstChildElement("link").text();
if (!title.isEmpty() and !desc.isEmpty() and !urirss.isEmpty()) {
position++;
if (position < limiter) {
contingent.insert(position,QStringList() << encodeBase64(urirss) << encodeBase64(title) << encodeBase64(desc));
}
}
child = child.nextSiblingElement("item");
}
xmlfile.close();
return contingent;
}

wysota
27th April 2008, 01:22
Attribute is not the same as tag, thus attribute("name") return an empty value, because there is no such attribute. Instead of using attribute(), use QDomElement::text() to retrieve the "value" of each tag.