Quick Linq to XML question
-
I'm starting out with linq to xml and have a quick question: I have the following xml-file: <countries> <country code="AF" iso="4">Afghanistan</country> <country code="AL" iso="8">Albania</country> <country code="DZ" iso="12">Algeria</country> <country code="AS" iso="16">American Samoa</country> <country code="AD" iso="20">Andorra</country> . . . How can I get a result containing all the country names by using a linq expression? I tried the following but it only gives me "Afghanistan": XDocument xmlDoc = XDocument.Load("countries.xml"); var countries = from country in xmlDoc.Descendants("countries") select new { Name = country.Element("country").Value, }; Thanks for help!
-
I'm starting out with linq to xml and have a quick question: I have the following xml-file: <countries> <country code="AF" iso="4">Afghanistan</country> <country code="AL" iso="8">Albania</country> <country code="DZ" iso="12">Algeria</country> <country code="AS" iso="16">American Samoa</country> <country code="AD" iso="20">Andorra</country> . . . How can I get a result containing all the country names by using a linq expression? I tried the following but it only gives me "Afghanistan": XDocument xmlDoc = XDocument.Load("countries.xml"); var countries = from country in xmlDoc.Descendants("countries") select new { Name = country.Element("country").Value, }; Thanks for help!
Your Linq query is asking for the wrong thing from the XDocument. The
Descendents()
method returns descendents of the object (in this case, the XDocument) which have the specified name (in this case 'countries'). So it is yielding a single enumerable element (because your XML Document has only one element). What you really need is to get the 'country' descendents of the XDocument:from xmlDoc.Descendents("country")
and then just get theValue
property of the elements of the enumeration. Here's some code that works for you:var countries = from country in xmlDoc.Descendants("country") select new { Name = country.Value };
-
I'm starting out with linq to xml and have a quick question: I have the following xml-file: <countries> <country code="AF" iso="4">Afghanistan</country> <country code="AL" iso="8">Albania</country> <country code="DZ" iso="12">Algeria</country> <country code="AS" iso="16">American Samoa</country> <country code="AD" iso="20">Andorra</country> . . . How can I get a result containing all the country names by using a linq expression? I tried the following but it only gives me "Afghanistan": XDocument xmlDoc = XDocument.Load("countries.xml"); var countries = from country in xmlDoc.Descendants("countries") select new { Name = country.Element("country").Value, }; Thanks for help!
Can you get a list of country: :)
XDocument xmlDoc = XDocument.Load("countries.xml"); List countries = from country in xmlDoc.Descendants("country") select new { Name = country.Value, };