I have an IEnumerable<XElement>
object that I want to query based on a certain node value, but continually get a null element
error. How do I select the value of two elements based on the value of a searched element? I am attempting to return firstName
and lastName
where ID == somevalue
.
Here is the structure of my XML:
<Profile>
<ID>123</ID>
<firstName>Not</firstName>
<lastName>Registered</lastName>
</Profile>
Snippet of my query:
XDocument xdoc = XDocument.Load(someXml);
IEnumerable<XElement> nodes = xdoc.Root.Elements();
XNamespace ns = "xmlNamespace";
var name = nodes.Elements(ns + "firstName")
.Where(x => (int)x.Element(ns + "ID") == 123)
.SingleOrDefault();
I was basing my query on this article, but I still can't find a mixture that returns what I want.
UPDATE
I have tried the suggested answers below and still see no results or receive an Object reference not set to an instance of an object
exception.
I am still working through the issue and am now trying this:
var result = xdoc
.Descendants(ns + "Profile")
.Where(x => (int)x.Element(ns + "ID") == 1)
.Select(x => new { FirstName = (string)x.Element(ns + "firstName"), LastName = (string)x.Element(ns + "lastName") })
.FirstOrDefault();
When stepping through this, the query hangs after running the Where
clause.