Blank out put when i am trying to parse the xml file using QXmlStreamReader Class
-
@BinuJanardhanan
did you read the docs about readElementText()?! -
@raven-worx Yes but its showing same.
-
@BinuJanardhanan
it shows what "same"?!First of all it says that you need to be in a StartElement state, which you are not. You are in the StartDocument state.
Second it says it reads text betwen Start- and End-Element. The only elements in your XML example are the childA and childB elements.QXmlStreamReader is a parser. If you want the input read from the set QIODevice directly, like you also already did.
-
@raven-worx Could you explain with an example?
-
@BinuJanardhanan
an example of what? I do not even know what you are trying to achieve?
If you just want to output the contents of the XML file then go the (working) second approach of yours.
If you need to parse the XML file (handle it's contents) then you need to go the QXmlStreamReader way.
For this simply callxml.readNext()
like you already do, but check the return value of it and react to it accordingly. -
@raven-worx I am trying to parse a xml file.
But readnext not read any token from the xml.
How i can i solve the issue ? -
-
@raven-worx said in Blank out put when i am trying to parse the xml file using QXmlStreamReader Class:
For this simply call xml.readNext() like you already do, but check the return value of it and react to it accordingly.
read again this comment of mine and see QXmlStreamReader::TokenType enum
-
@VRonin Thanks for your reply.
I have tried the first example. But nothing is showing in the output.
XML is given below<?xml version="1.0" encoding="UTF-8"?> <root> <childA>text1</childA> <childA>text2</childA> <childB>text3</childB> <childA>text4</childA> </root>
And the code for parse the above xml is :
QFile file("test.xml"); if(!file.open(QFile::ReadOnly | QFile::Text)){ qDebug() << "Cannot read file" << file.errorString(); exit(0); } QXmlStreamReader reader(&file); if (reader.readNextStartElement()) { if (reader.name() == "root"){ while(reader.readNextStartElement()){ if(reader.name() == "childA"){ QString s = reader.readElementText(); qDebug(qPrintable(s)); } else reader.skipCurrentElement(); } } else reader.raiseError(QObject::tr("Incorrect file")); }
In this code ,compiler not enter to if (reader.readNextStartElement()) . reader.readNextStartElement() always return false.
What is the issue?
Please help I am a beginner . -
Try:
QFile file("test.xml"); if(!file.open(QFile::ReadOnly)){ qDebug() << "Cannot read file" << file.errorString(); exit(0); } QXmlStreamReader reader(&file); bool insideRoot = false; while(!reader.atEnd() && !reader.hasError()){ switch(reader.readNext()){ case QXmlStreamReader::StartElement: if(reader.name()=="root") insideRoot =true; else if(reader.name()=="childA" && insideRoot){ qDebug() << reader.readElementText(); } break; case QXmlStreamReader::EndElement: if(reader.name()=="root") insideRoot =false; break; } }