14

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++;
lsdavies
  • 187
  • 1
  • 13
  • No worries, I restored it just now before I read your message here. Thank you for the excellent code! – lsdavies Feb 12 '13 at 03:09

3 Answers3

19

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.

zeuxcg
  • 8,703
  • 1
  • 22
  • 33
3

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

xMainNode.select_nodes( "name" ).size()
arayq2
  • 2,295
  • 13
  • 21
1
int children_count(pugi::xml_node node)
{
  int n = 0;
  for (pugi::xml_node child : node.children()) n++;
  return n;
}
Pedro Vicente
  • 443
  • 1
  • 5
  • 17