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.
XPath支持一些名为Axis说明符的东西,所以你要找的代码是
node.SelectNodes("descendant::*").Count
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.
using System.Xml.Linq;
node.DescendantNodes().Count();
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;
}
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;
}
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
//*
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.