Question

Does a pugixml node object have a number-of-child-nodes method? I cannot find it in the documentation and had to use an iterator as follows:

int n = 0;
for (pugi::xml_node ch_node = xMainNode.child("name"); ch_node; ch_node = ch_node.next_sibling("name")) n++;
Was it helpful?

Solution

There is no built-in function to compute that directly; one other approach is to use std::distance:

size_t n = std::distance(xMainNode.children("name").begin(), xMainNode.children("name").end());

Of course, this is linear in the number of child nodes; note that computing the number of all child nodes, std::distance(xMainNode.begin(), xMainNode.end()), is also linear - there is no constant-time access to child node count.

OTHER TIPS

You could use an expression based on an xpath search (no efficiency guarantees, though):

xMainNode.select_nodes( "name" ).size()
int children_count(pugi::xml_node node)
{
  int n = 0;
  for (pugi::xml_node child : node.children()) n++;
  return n;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top