1

I am trying to switch from XmlDocument to Linq, and am struggling to get what I want.

I have XML similar to this,

<root>
<Surfer Status='5'>
    <Name>Billy</Name>
    <County>Cornwall</County>
</Surfer>
<Surfer Status='5'>
    <Name>Tim</Name>
    <County>Cornwall</County>
</Surfer>
<Surfer Status='10'>
    <Name>Ryan</Name>
    <County>Devon</County>
</Surfer>
</root>

I can count all the surfers like this.

XDocument X = XDocument.Load("Surfers.xml");
int Total = X.Descendants("Surfer").Count();

I was hoping to count all the Surfers with a Status of 5 like this

int fives = X.Descendants["Surfer[@Status='5']").Count();

but it doesn't work!

1
  • What do you mean by it doesn't work ? Are you getting an error message ? Or are you simply not getting the expected result ? Commented Nov 22, 2015 at 22:40

2 Answers 2

1

You can use Count overload which takes a predicate

int fives = X.Descendants("Surfer").Count(x => x.Attribute("Status")?.Value == "5");

x.Attribute("Status") will retrieve the Status attribute from the Surfer element and ?. operator prevents NullReferenceException if any of Surfer elements does not have Status attribute.

Sign up to request clarification or add additional context in comments.

Comments

1

Use Where:

int fives = X.Descendants("Surfer").Where(s => (int)s.Attribute("Status") == 5).Count();

or if you really want to use XPath expression you can do it after adding using System.Xml.XPath and using XPathSelectElements:

int fives = X.XPathSelectElements("Surfer[@Status='5']").Count();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.