0

I am trying to count all the nodes within an xml document using XPathDocument

the code im using is

var xmlPathDoc = new XPathDocument(new StringReader(xml));
XPathNavigator documentNav = xmlPathDoc.CreateNavigator();

is there a way to count these when i dont know the name of the nodes

i wanted to use something like

int nodeCount = documentNav.Select("/").Count;

but wasnt sure what to put in the select part

thanks

simon

level_zebra
  • 1,503
  • 6
  • 25
  • 44

3 Answers3

3
XmlNode node = myDoc.SelectSingleNode("/");

int i = node.SelectNodes("descendant::*").Count;

Also refer Count Total Number of XmlNodes in C#

Community
  • 1
  • 1
Madurika Welivita
  • 890
  • 1
  • 10
  • 19
2

You can use XDocument.Descendents and count them:

var doc = XDocument.Parse(xml);
var count = doc.Descendants().Count();
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
0

You do not need XPath. First get the DOM object and get the nodelist of all elements and get its count.

public virtual XmlNodeList GetElementsByTagName(String tagname )


    Returns a NodeList of all the Elements with a given tag name in the order 
    in which they are encountered in a preorder traversal of the Document tree.

        Parameters:
            tagname - The name of the tag to match on. The special value "*"
            matches all tags. 
        Returns:
            A new NodeList object containing all the matched Elements.
srini.venigalla
  • 5,137
  • 1
  • 18
  • 29