开发者

How to parse an XML string in Qt

开发者 https://www.devze.com 2023-01-07 15:52 出处:网络
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.

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?


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();


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;
}


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

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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号