How to parse an XML string in Qt

I am developing the application in that after creating the web service I received a response from the server, which is in the XML tag.

Answer:

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

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

+5
source share
5 answers

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();
+18
source

The best way is to use the Qt XML Patterns module.

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

+1
source

...!

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

I wrote a simple wrapper for some of the QDom * classes, which simplifies working with XML in Qt.

For instance:

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

Or even like this:

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

"*" - all children of the tree from the current node. "" - only children of the first generation. e - node. c is a list of node children. all children found are also stored in the "c" attribute.

0
source

All Articles