I'm new to Qt and I'm learning something new every day.
Currently, I'm developing a small application for my Nokia N900 in my free time.
Everything is fine, I am able to compile and run Maemo applications on the device.
I've just learned about the foreach
keyword in Qt. (I know it is not in C++, so I didn't think about it until I accidentally stumbled upon a Qt doc that mentioned it.)
So, I decided to change my quite annoying and unreadable loops to foreach, but I failed with this:
QDomNodeList list = doc.lastChild().childNodes().at(1).firstChild().childNodes();
for (int x = 0; x < list.count(); x++)
{
QDomElement node = list.at(x).toElement();
// Do something with node
}
This is how I tried:
foreach (QDomElement node, doc.lastChild().childNodes().at(1).firstChild().childNodes())
{
// Do something with node
}
For some reason the above code doesn't even compile. I get cryptic error messages from the compiler.
Could someone please explain to me how to get it right?
If the foreach
loop doesn't support QDomNodeList
, is there a way to handle XML files which supports foreach
?
EDIT:
To clarify, // Do something with node
is the following in this case:
EveCharacter chr;
chr.setName(node.attribute(EVE_NAME));
chr.setId(node.attribute(EVE_CHARACTER_ID).toInt());
acc->addCharacter(chr);
Where acc is of type EveAccount
, which stores data in a QList<EveCharacter>
.
The uppercase symbols are compile-time constant strings.
(I'm creating a client for the EVE Online API. This is from the method that receives the account characters XML and interprets it.)
This is how I create doc
:
QDomDocument doc;
doc.setContent(reply->readAll());
Note that reply
is a QNetworkReply*
which is sent back from a QNetworkAccessManager
.
However, as the EVE API works with XML, I do a lot of XML parsing very similar to this in many places in my application.
Most of the XMLs can be several hundred lines long and can contain quite non-regular data patterns, such as this one.
foreach
only supports the container classes, so you cannot use it with aQDomNodeList
.I'm not sure of you actual goal, but I find the
QXmlSimpleReader
andQXmlStreamReader
to be the easiest way to deal with XML.Edit to match question edit:
What you are trying to do looks like a prime candidate for XPath or XQuery. Take a look at the
QtXmlPatterns
module this will give you a set of character nodes without having to loop through all the other nodes.foreach
works with Qt Generic Containers. It doesn't look like QDomNodeList inherits from anything, so you can't useforeach
.Could you iterate through the node list and insert the nodes into a
QList<QDomElement>
?