Tirupati Balan
Tirupati Balan

Reputation: 674

How to parse an XML string in Qt

I am developing an application in that after making a web service I got the response from the server which is in the XML tag.

The response:

<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n
<string...... /\">Hello World</string>

I want to read only the "Hello World" string. How should I parse it?

Upvotes: 5

Views: 16447

Answers (5)

guruz
guruz

Reputation: 1614

The best way is to use Qt's XML Patterns module.

http://doc.qt.io/archives/4.6/qxmlquery.html

Upvotes: 1

Live
Live

Reputation: 2001

You could use the the QString::replace ( const QString & before, const QString & after, Qt::CaseSensitivity cs = Qt::CaseSensitive ) to replace the XML tokens by blanks.

If the XML tags you will be receiving can be many things, I woulds suggest you implement an XML handler to be able to strip the XML tags from you string.

Upvotes: 0

off_border
off_border

Reputation: 11

I wrote a simple wrapper on some QDom* classes that makes working with XML in Qt more easy.

For example:

myxmlmap->$("tagnameq1")->$("tagname2.")->$("@attrname=attrvalue*").c.length()

Or even that way:

myxmlmap->$("tagname1>tagname2.>@attrname=attrvalue*").c.at(2).e.text()

"*" - all children in tree from the current node. "." - only the 1st generation children. e - node element. c - list of node children. all found children also stored in "c" attribute.

Upvotes: 0

Muhammad Suleman
Muhammad Suleman

Reputation: 2922

try this... !

QFile* file = new QFile(fileName);
if (!file->open(QIODevice::ReadOnly | QIODevice::Text))
{
     QMessageBox::critical(this, "QXSRExample::ReadXMLFile", "Couldn't open xml file", QMessageBox::Ok);
     return;
}

QXmlStreamReader xml(file);
QXmlStreamReader::TokenType token;
while(!xml.atEnd() && !xml.hasError())
{
    /* Read next element.*/
    token = xml.readNext();
    /* If token is just StartDocument, we'll go to next.*/
    if(token == QXmlStreamReader::StartDocument)
        continue;


 if(token == QXmlStreamReader::Characters)
     QMessage::information(this,"all text", xml.text().toString());
 continue;
}

Upvotes: 1

metdos
metdos

Reputation: 13929

I hope this helps:

QByteArray xmlText;
//Get your xml into xmlText(you can use QString instead og QByteArray)
QDomDocument doc;
doc.setContent(xmlText);
QDomNodeList list=doc.elementsByName("string");
QString helloWorld=list.at(0).toElement().text();

Upvotes: 19

Related Questions