Answer: Let us look at the below situation
<?xml version='1.0' encoding='UTF-8'?>
<Countries>
<State Name = 'Karnataka'>
<City Name='Bangalore' />
<City Name= 'Guledgudda' />
<City Name= 'Hubli' />
<City Name= 'Tumkur' />
</State>
</Countries>
The challenge is to get the City Names using XDocument class. The below code will help us to do so
string inputXml = @"<?xml version='1.0' encoding='UTF-8'?>
<Countries>
<State Name = 'Karnataka'>
<City Name='Bangalore' />
<City Name= 'Guledgudda' />
<City Name= 'Hubli' />
<City Name= 'Tumkur' />
</State>
</Countries>";
XDocument countrySource = XDocument.Parse(inputXml);
//The query
countrySource
.Descendants("State")
.SelectMany(i => i.Elements())
.ToList()
.ForEach(i=>Console.WriteLine((string)i.Attribute("Name")));
//Output
Bangalore
Guledgudda
Hubli
Tumkur
Asked In: Many Interviews |
Alert Moderator