Q:

QXmlStreamReader: Put readNext() at the start or at the end of the loop?

When reading Xml data with Qt's QXmlStreamReader:
Should readNext() be put at the beginning or at the end of the while(!reader.atEnd()) loop? I've run across many examples that put it at the beginning, but also quite a few that put it at the end.
QXmlStreamReader reader;
while(!reader.atEnd())
{
    // <- Put reader.readNext() here?

    QXmlStreamAttributes currentAttributes = reader.attributes();
    // Do something with the attributes
    // ...

    // <- Or put reader.readNext() here?
}

My gut says it should be at the start of the loop (to er... read the next xml token, populate attributes() with new data etc.) but I'm not 100% certain (due to the quite a few examples that put readNext() at the end of the loop). Putting it at the end probably would also give me an off-by-one error (atEnd() becomes true with the last readNext(), leaving the last token unprocessed), correct?

A:

You need to understand how the class works and what each function does. As a demonstration let's consider the following simple example:
QXmlStreamReader reader("<info name=\"Foo\"/>");
while (!reader.atEnd()) {
  //reader.readNext();
  auto currentToken = reader.tokenType();
  qDebug() << currentToken;
  reader.readNext();
}

If we run it and print out the values of current token (XML) on each iteration we will get the following sequences:

StartDocument, StartElement, EndElement, EndDocument (readNext() call is at the beginning),
NoToken, StartDocument, StartElement, EndElement (readNext() call is at the end)

As you can see, if readNext() is at the beginning of the loop you can process more elements, including both document's begin and end elements too. Thus the early call of QXmlStreamReader::readNext() in such loops is better.

