How to get the Value of attribute from XML using XDocument class?

 Posted by Niladri.Biswas on 7/12/2012 | Category: LINQ Interview questions | Views: 3386 | Points: 40
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 

Comments or Responses

Login to post response