How do I use foreach with QDomNodeList in Qt?

。_饼干妹妹 提交于 2019-12-12 08:24:29

问题


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.


回答1:


foreach only supports the container classes, so you cannot use it with a QDomNodeList.

I'm not sure of you actual goal, but I find the QXmlSimpleReader and QXmlStreamReader 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.




回答2:


foreach works with Qt Generic Containers. It doesn't look like QDomNodeList inherits from anything, so you can't use foreach.

Could you iterate through the node list and insert the nodes into a QList<QDomElement>?



来源:https://stackoverflow.com/questions/2914631/how-do-i-use-foreach-with-qdomnodelist-in-qt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!