Reputation: 24092
I am trying to get the number of children that a node has but the only thing I can get is whether is has any children not how many. For instance :
I am using Xpath in C# (XPathNodeIterator
, XPathDocument
and XPathNavigator
)
EDIT:
iterator.Count
is not what I want to achieve because it returns the number of all the nodes returned by the expression. I would like to know how many child nodes are there 'below' the iterator.Current
This is the Xml file I work with (as for an example)
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>two of our famous Belgian Waffles with plenty of real maple syrup</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>light Belgian waffles covered with strawberries and whipped cream</description>
<calories>900</calories>
</food>
</breakfast_menu>
`
My code:
XPathDocument document = new XPathDocument(@"C:\\xmls\\chair1.xml");
XPathNavigator navigator = document.CreateNavigator();
XPathNodeIterator iterator = navigator.Select("//*");
while (iterator.MoveNext())
{
stringList.Add(iterator.Current.Name);
if(iterator.Current.HasChildren) stringList.Add(iterator.Current.Value);
stringList.Add(" ------- ");
}
And what it produces
Upvotes: 2
Views: 4256
Reputation: 243469
A pure XPath solution -- use this XPath expression:
count(//*)
Or, the complete C# code (seems to be the shortest of all offered so far :)
(int)navigator.Evaluate("count(//*)")
Or, if you want to get the count of children of the current node, use:
(int)iterator.Current.Evaluate("count(*)")
Upvotes: 2
Reputation: 670
var count = iterator.Count;
Play with reference! http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnodeiterator.aspx
Upvotes: 0
Reputation:
XPathNodeIterator.Count
Should give you the Children Count, Or 0 in case no selected nodes.
Upvotes: 4