5

I'm trying to find a way to get the total number of child nodes from an XmlNode recursively.

That it is to say I want to count all the children, grand children etc.

I think its something like

node.SelectNodes(<fill in here>).Count

but I don't know what the XPath is.

svick
  • 236,525
  • 50
  • 385
  • 514
mat-mcloughlin
  • 6,492
  • 12
  • 45
  • 62

6 Answers6

8

XPath supports something called Axis specifier, so the code you're looking for is

node.SelectNodes("descendant::*").Count
svick
  • 236,525
  • 50
  • 385
  • 514
4

The XPath you are after is:

descendant::node() (1)

or

descendant::* (2)

The first XPath expresion (1) above selects any node (text-node, processing-instruction, comment, element) in the subtree rooted by the current node.

(2) selects any element node in the subtree rooted by the current node.

Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
  • (2) is equivalent to `descendant-or-self::*`, but the question was only for the child nodes, not including the current node (of course, it's just a matter of subtracting 1) – svick Apr 15 '10 at 13:16
  • This is also correct! but he needs the points more than you :S – mat-mcloughlin Apr 15 '10 at 14:28
3
using System.Xml.Linq;

node.DescendantNodes().Count();
Mel Gerats
  • 2,234
  • 1
  • 16
  • 33
0

If you're doing an unfiltered count, which your question implies, you could just traverse the them using the ChildNodes property:

private int CountChildren(XmlNode node)
{
   int total = 0;

   foreach (XmlNode child in node.ChildNodes)
   {
      total++;
      total += CountChildren(child);
   }
   return total;
}
Steve Danner
  • 21,818
  • 7
  • 41
  • 51
0

You could use somthing like this:

private static int CountNodes(XmlNode node)
{
    int count = 0;

    foreach (XmlNode childNode in node.ChildNodes)
    {
        count += CountNodes(childNode);
    }

    return count + node.ChildNodes.Count;
}
Andrew Bezzub
  • 15,744
  • 7
  • 51
  • 73
-1

I think this will do it for you though not through xPath:

void CountNode(XmlNode node, ref int count)
{
    count += node.ChildNodes.Count;

    foreach (XmlNode child in node.ChildNodes)
    {
        CountNode(child, ref count);
    }
}

For reference here is a link to the count function in xpath.

http://msdn.microsoft.com/en-us/library/ms256103.aspx

so if you were looking for all the same type of nodes you could do

//Your_node

to select all the nodes

//*
kemiller2002
  • 113,795
  • 27
  • 197
  • 251