views:

1333

answers:

1

I would like to use Linq to Xml to get a single XElement from a .xml file by attribute name, similar to how you retrieve single objects in Linq to Sql by Id below:

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

Is this possible?

+4  A: 

Absolutely. Just use something like:

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

There may be a more efficient way of doing it, admittedly...

Jon Skeet
this statement does have one issue, I found, and it is that the XElement object doesn't have a HasAttribute property. If I remove that from the Lambda expression it works great!.
Mr. Kraus
I also made the following statement work as well!xmlDoc.Descendants("Site").Single(p => (string)p.Attribute("Name") == rootName);where rootName is a string type.
Mr. Kraus
What does that do for elements which don't have a Name attribute though?
Jon Skeet
I would have used SingleOrDefault to avoid the null ref exception and then make a null check afterwards.
Johan Leino