Alex Angas
Alex Angas

Reputation: 60027

How do I find an XML element by attribute using LINQ to XML?

I'm learning LINQ to XML and need to find the existence of an element with a particular attribute. At the moment I'm using:

XElement groupCollectionXml = XElement.Parse(groupCollection.Xml);
IEnumerable<XElement> groupFind =
    from vw in groupCollectionXml.Elements("Group")
    where (string) vw.Attribute("Name") == groupName
    select vw;

if (groupFind.Count() == 0)
    return false;
else
    return true;

I know there is a more concise way of doing this, probably using Any(), but I'm not sure how to rewrite the query to use it. Does anyone have some good advice? Thanks.

Upvotes: 3

Views: 5153

Answers (3)

user73259
user73259

Reputation:

groupCollectionXml.
    Elements("Group").
    Where(item=>String.
        Equals(item.Attribute("Name"), groupName, OrdinalIgnoreCase)).
    Any();

if you want it all on one line

Upvotes: 2

eglasius
eglasius

Reputation: 36037

groupCollectionXml.Elements("Group").Any(
    vw=>(string)vw.Attribute("Name") == groupName
  );

Upvotes: 6

Alex Angas
Alex Angas

Reputation: 60027

Thanks to the other two answers. I combined the conciseness of one with the correctness of another, then stirred and came up with this which works well:

groupCollectionXml.Elements("Group").Any(
  vw => string.Equals(vw.Attribute("Name").Value, groupName, StringComparison.OrdinalIgnoreCase)
);

Upvotes: 2

Related Questions