开发者

How to get node count with XPathDocument and C#?

开发者 https://www.devze.com 2023-02-16 13:57 出处:网络
I have a simple xml document and I want to get the count of a certain node. How can I do this? Right now I am using the following syntax to get the node.

I have a simple xml document and I want to get the count of a certain node. How can I do this? Right now I am using the following syntax to get the 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");


Do you want to count the number of instances of api/error? If so try:

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


You can use this:

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


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

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

For example, in the given xml the 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 the hierarchical structure, then 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 the result as 3.

0

精彩评论

暂无评论...
验证码 换一张
取 消