1
Sam
Male
423
This code will work even if there is any Phone
elements exist for employee:
var emplyees =
from emp in emplyeeDetails.Descendants("Employee").Take(10)
let phones = emp.Descendants("Phone")
orderby (int)emp.Element("EmpId")
select new
{
Id = (int)emp.Element("EmpId"),
Name = (string)emp.Element("Name"),
Sex = (string)emp.Element("Sex"),
WorkPhone = (string)phones.FirstOrDefault(p => (string)p.Attribute("Type") == "Work"),
HomePhone = (string)phones.FirstOrDefault(p => (string)p.Attribute("Type") == "Home")
};
Use casting elements to string
, int
, etc instead of accessing Value
property. Why? Because if there is some missing element or attribute in your xml, then you will get a NullReferenceException
. But casting will return default value instead. So, code above will parse even xml like this:
1
Sam
423-555-0124
524-777-1234