STF STF - 1 year ago 86
C++ Question

QXmlStreamReader.readNextStartElement() reads start elements twice

I have a QXmlStreamReader variable and I want it to go over my xml file- QFile, and read all the start elements by the function readNextStartElement().
But it gives me every start tag twice.

Here is my code:

QXmlStreamReader* xmlReader = new QXmlStreamReader(orFile);
xmlReader->readNextStartElement();
std::string tagName = (orXmlReader->name()).toLocal8Bit().constData();
cout << tagName;
xmlReader->readNextStartElement();
tagName = (orXmlReader->name()).toLocal8Bit().constData();
cout << tagName;


Can someone help me find a solution? I there another function that can read normally the start elements?

Answer Source

That API is confusing indeed and the documentation doesn’t help much for this particular case.

I think two things are worth mentioning:

  1. The function is usually used in a context where you consume the content of the current element before calling readNextStartElement() again, e.g. readElementText() to get the content. If used like that, the problem doesn’t occur.
  2. When calling the function while the position is already a start element (as it is after the tag was reported the first time), the function returns false without changing the position. Only the next call moves the position (and returns true in the good case).

So in our example, you can either actually read the content of the tag, or check the return value of readNextStartElement() and ignore it when it returns false. That might then ignore some valid error cases though.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download