How to get node score using XPathDocument and C #?

I have a simple XML document and I want to get the count of a specific node. How can i do this? Right now I am using the following syntax to get node.

// send request and strore in xpath doc (read-only) XPathDocument xDoc = new XPathDocument(requestURL); // Create navigator XPathNavigator navigator = xDoc.CreateNavigator(); XPathNavigator navError = navigator.SelectSingleNode("/api/error"); 
+4
source share
3 answers

Want to count the number of api / error instances? If yes, try:

 int errorCount = navigator.Select("/api/error").Count; 
+5
source

You can use this:

 int count = navigator.Select("/api/error").Count; 
+2
source

Using LINQ , you can count the number of node instances (regardless of hierarchical position),

 int nodeCount; using (StreamReader reader = new StreamReader(xmlFilePath)) { XElement rootElement = XElement.Load(reader); nodeCount = rootElement.Descendants(nodeName).Count(); } 

For example, in this xml nodeCount will be 4 ( nodeName is "b"),

 <a> <b>1</b> <b>2</b> <b> <c>3</c> </b> <d> <b>4</b> </d> </a> 

If you want to maintain a hierarchical structure, use this code

 string nodeXPath = "./b"; using (StreamReader reader = new StreamReader(xmlFilePath)) { XElement rootElement = XElement.Load(reader); nodeCount = rootElement.XPathSelectElements(nodeXPath).Count(); } 

The result for the same example will now give a result as 3.

0
source

Source: https://habr.com/ru/post/1343390/


All Articles