How to get Single XElement object using Linq to Xml?
-
03-07-2019 - |
Question
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?
Solution
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...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow