xml-parsingcountsizepugixml

pugixml number of child nodes


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++;

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.