Patryk
Patryk

Reputation: 24092

How can I check how many children does a node have?

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

enter image description here

Upvotes: 2

Views: 4256

Answers (4)

Dimitre Novatchev
Dimitre Novatchev

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

Reza ArabQaeni
Reza ArabQaeni

Reputation: 4907

iterator.Current.SelectChildren(XPathNodeType.All).Count

Upvotes: 7

nikola-miljkovic
nikola-miljkovic

Reputation: 670

var count = iterator.Count;

Play with reference! http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnodeiterator.aspx

Upvotes: 0

user915331
user915331

Reputation:

XPathNodeIterator.Count 

Should give you the Children Count, Or 0 in case no selected nodes.

Upvotes: 4

Related Questions