I\'m new to LINQ and XML parsing and rather new to C# programming. For the following XML structure, I\'m trying to extract the nested elements:
You can do it this way using linq:
var result = from p in xmlDoc.Descendants("person")
from a in p.Descendants("address")
where p.Element("personNumber").Value == "2"
select new
{
City = a.Element("city").Value,
Location = a.Element("location").Value
};
Sth like the following should work:
XDocument xmlDoc = XDocument.Load(@"mypath\persons.xml");
var q = from e in xmlDoc.Descendants("person")
where e.Element("personNumber").Value == "2"
let address = e.Descendants("address")
from a in address
select new {
city = a.Element("city").Value,
location = a.Element("location").Value
};
With the sample xml provided in the OP the above linq query produces the following result:
[0] = { city = "XXX", location = "1" }
[1] = { city = "YYY", location = "2" }