2011-08-24 42 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。 –