Reputation: 305
I have created a function (using PugiXML, specifically) to iterate all Document Tree nodes to find a specific node. To do this, I have created a function that contains a for loop which iterates through node siblings and is called recursively to iterate through the entire depth of the tree and find a specific node (not shown in the code). Although the specific use is not precisely relevant I have two main questions:
Is there a better way to do this? As I understand, this mixture of iterative and recursive logic is not a good coding practice. Does anyone else have suggestions on another method I should implement? Also, leading me to question 2:
Is there an elegant way to break MANY nested for loops? I use goto
with my current code, but have been told that using it is a bad coding practice, and it definitely should not be used in a recursive algorithm. I also use two global variables because of the limitations
My code:
xml_node recursiveFind(xml_node node)
{
for (node = node; node; node = node.next_sibling())
{
if (checkAttr(node) == 0)
{
cout << "found: " << node.name() << " attr: " << node.first_attribute().value() << endl;
found = true;
foundNode = node;
goto return_code;
}
else if (checkAttr(node) == 1 && found != true)
{
cout << "still looking: " << node.name() << " attr: " << node.first_attribute().value() << endl;
recursiveFind(node.first_child());
}
return_code:
return foundNode;
}
For a quick walkthrough of my code, the for loop iterates through siblings, then a second function, checkAttr()
is called with the current node as a parameter to check whether it is the node I am searching for, and if it returns 0 (true), a global variable is set that is supposed to stop the recursive call (in the following else if
statement. Then, another global variable with the selected node is created so that it can be returned by the goto
call. Adding any sort of break in the for loop is impossible as many, many, many nested loops are generated from the recursive calls. Hopefully, this question is able to also assist others using PugiXML.
Upvotes: 0
Views: 150
Reputation: 305
After further research, I realized that I had missed a fundamental part of recursive functions, driver and recursive functions. Thank you to @user4581301 for your comment. For other PugiXML users, I would recommend using XPath as it is probably more optimized than anything you will write ;)
Upvotes: 0