2011-08-24 32 views
2

我通過WebClient方法調用restful服務來返回一些XML。然後,我想通過XML解析,從每個節點中提取特定的字段,並將其轉換爲數組。將XML解析爲對象數組 - 使用Silverlight/Windows Phone

我有代碼工作來檢索XML並將其填充到列表框中。出於某種原因,我無法弄清楚如何將其轉換爲對象數組。

到目前爲止的代碼:

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; 
     } 
    } 

} 

我怎樣才能把每個節點爲對象的數組?

非常感謝提前! 請問。

編輯:XML看起來是這樣的: 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> 
+0

使用實體類創建XML節點的實體並將其反序列化爲IEnumerable。 – Rumplin

+0

你的XML是什麼樣的? – Praetorian

+0

增加了關於XML結構的額外信息。 @Rumplin - 不知道你的評論意味着什麼...... –

回答

2

有什麼不對

// 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); 

這會給你DummyClass對象的數組,從LINQ查詢產生的IEnumerable<DummyClass> 。另外,甚至不需要數組。如果您只需對數據進行迭代,則只需在data對象上執行foreach即可。

+1

是的 - 那是做的伎倆。有時候很簡單......謝謝,@Nate。 –