How to get Single XElement object using Linq for Xml?

I would like to use Linq for Xml to get one XElement from an .xml file by attribute name, similar to how you extract individual objects in Linq to Sql by Id below:

var singleDog = context.Dogs.Single(p => p.Id == int.Parse(Id));

Is it possible?

+3
source share
1 answer

That's right. Just use something like:

xdoc.Descendants()
    .Where(x => x.HasAttribute("id") && x.Attribute("id")==id)
    .Single();

Maybe a more efficient way to do this, admittedly ...

+7
source

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


All Articles