使用Silverlight / Windows Phone将XML解析为对象数组

时间:2011-08-24 20:04:40

标签: c# xml silverlight windows-phone-7 linq-to-xml

我通过WebClient方法调用一个restful服务来返回一些XML。然后,我想解析XML,从每个节点中提取特定字段,然后将其转换为数组。

我有代码正在检索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>

1 个答案:

答案 0 :(得分: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>

此外,甚至可能不需要阵列。如果您需要做的就是迭代数据,只需在foreach对象上执行data即可。