Parse XML into an array of objects - with Silverlight / Windows Phone
Someone asked on Stack Overflow:
I am calling a restful service via the WebClient method to return some XML. I would then like to parse through the XML, extract specific fields out of each node, and turn that into an array.
I have the code working to retrieve the XML and populate it into a listbox. For some reason I cannot work out how to turn that into an array of objects.
Code so far:
private void button1_Click(object sender, RoutedEventArgs e) { WebClient wc = new WebClient(); wc.DownloadStringCompleted += HttpsCompleted; wc.DownloadStringAsync(new Uri(requestString)); } private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e) { if (e.Error == null) { XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None); var data = from query in xdoc.Descendants("entry") select new DummyClass { Name = (string)query.Element("title"), Kitty = (string)query.Element("countryCode") }; listBox1.ItemsSource = data; } } }How can I turn each node into an object in an array?
Many thanks in advance! Will.
EDIT: The XML looks like this: http://api.geonames.org/findNearbyWikipedia?lat=52.5469285&lng=13.413550&username=demo&radius=20&maxRows=5
<geonames> <entry> <lang>en</lang> <title>Berlin Schönhauser Allee station</title> <summary> Berlin Schönhauser Allee is a railway station in the Prenzlauer Berg district of Berlin. It is located on the Berlin U-Bahn line and also on the Ringbahn (Berlin S-Bahn). Build in 1913 by A.Grenander opened as "Bahnhof Nordring" (...) </summary> <feature/> <countryCode>DE</countryCode> <elevation>54</elevation> <lat>52.5494</lat> <lng>13.4139</lng> <wikipediaUrl> http://en.wikipedia.org/wiki/Berlin_Sch%C3%B6nhauser_Allee_station </wikipediaUrl> <thumbnailImg/> <rank>93</rank> <distance>0.2807</distance> </entry> </geonames>
I posted the following answer, which was chosen as the accepted answer and received 2 upvotes:
What is wrong with
// convert IEnumerable linq query to an array
var array = data.ToArray(); // could also use .ToList() for a list
// access like this
MessageBox.Show(array[0].Kitty);
This will give you an array of DummyClass objects, from the IEnumerable<DummyClass> generated by the linq query.
Additionally, an array may not even be required. If all you need to do is iterate over the data, you can simply do a foreach on your data object.
Originally posted on Stack Overflow — 2 upvotes (accepted answer). Licensed under CC BY-SA.