rapidxml: how to iterate through nodes? Leaves out

2020-04-05 08:45发布

问题:

Using rapidxml I'm wanting to loop through a set of nodes, and am using what I found to be the best way to do this (from trusty stackoverflow, the doc doesn't appear to have an example of iteration):

while (curNode->next_sibling() !=NULL ) {
    string shiftLength = curNode->first_attribute("shiftLength")->value();
    cout << "Shift Length " << "\t" << shiftLength << endl;
    curNode = curNode->next_sibling();        
}

Unfortunately, on my OSX 10.6 this is leaving out the last sibling node - I guess because in the last iteration of the loop, next_sibling is called twice. I can get at this last node if I write, after the loop:

cout << " LAST IS: " << curNode->first_attribute("shiftLength")->value();

...but that's dodgy, and the program quits at that point.

First question: Could this be a unique foible of my setup (OSX 10.6) or have I coded wrong?

Second question: Does anyone have an example of what they believe is the correct way to iterate through an unknown number of XML nodes using rapidxml?

Thanks guys

Pete

回答1:

This is the proper way to iterate though all child nodes of a node in rapidxml:

xml_node<> *node = ...
for (xml_node<> *child = node->first_node(); child; child = child->next_sibling())
{
    // do stuff with child
}


回答2:

Here's the final code in working form:

while( curNode != NULL ) {

    string start = curNode->first_attribute("start")->value();
    string numStaff = curNode->first_attribute("numStaff")->value();
    cout << start << "\t" << numStaff << endl;
   curNode = curNode->next_sibling();
}


回答3:

while (curNode->next_sibling() !=NULL )

This says "while there's one more node left after the one I'm working on". That's why your loop's stopping early - when curNode is the final sibling, its "next_sibling" will be NULL. This test should work better:

while (curNode !=NULL )