尝试使用从API获取的xml数据填充列表框

时间:2014-01-29 19:54:32

标签: c# xml api visual-studio-2012 windows-phone-8

好的,我在这里为windows phone构建这个词典应用程序。它使用merriam-webster api,它将查询作为xml返回。我试图将其填充到具有来自xml元素的id的长列表选择器

这只是抛出一个线程退出,代码259错误,列表为空。请帮忙解决这个问题。

private void Button_Click(object sender, RoutedEventArgs e)
    {
        WebClient wcXML = new WebClient();
        wcXML.OpenReadAsync(new Uri("http://www.dictionaryapi.com/api/v1/references/medical/xml/" + MedSearch.Text + "?key=235089d7-eb18-47f6-9ab8-226685fc7d98"));
        wcXML.DownloadStringCompleted += new DownloadStringCompletedEventHandler(c_DownloadStringCompleted);
    }

    void c_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
            var s = e.Result;
            Debug.WriteLine(""+e.Result);
            var rssElement = XElement.Parse(s);
                            var items = from item in rssElement.Descendants("entry")
                          select new entry_list
                          {
                              id = item.Attribute("id").Value,
                              fl = item.Element("fl").Value,
                              def = item.Element("def").Element("sensb").Element("sens").Element("dt").Value

                          };

            listBox1.ItemsSource = items;

            //checking if anything is there.
            string result = "";

            foreach (entry_list i in items)
            {
                result += i.def;
            }
            resultsBlock.Text = result;

    }

1 个答案:

答案 0 :(得分:1)

您需要更改代码的顺序,因为事件应该在调用之前实现,如果您使用的是事件DownloadStringCompleted,那么您应该调用DownloadStringAsync而不是OpenReadAsync

            WebClient wcXML = new WebClient();
            wcXML.DownloadStringCompleted += wcXML_DownloadStringCompleted;
            wcXML.DownloadStringAsync(new Uri("http://www.dictionaryapi.com/api/v1/references/medical/xml/" + MedSearch.Text + "?key=235089d7-eb18-47f6-9ab8-226685fc7d98"));

现在,如果MedSearch.Text是“她”,那么e.Result将如下

<?xml version="1.0" encoding="utf-8" ?>
<entry_list version="1.0">
    <suggestion>hear</suggestion>
    <suggestion>Er</suggestion>
    <suggestion>ear</suggestion>
    <suggestion>aer-</suggestion>
    <suggestion>hair</suggestion>
    <suggestion>hour</suggestion>
    <suggestion>air</suggestion>
    <suggestion>Ar</suggestion>
    <suggestion>Ir</suggestion>
    <suggestion>OR</suggestion>
    <suggestion>hr</suggestion>
    <suggestion>ir-</suggestion>
    <suggestion>ur-</suggestion>
    <suggestion>hairy</suggestion>
    <suggestion>Haller</suggestion>
    <suggestion>hilar</suggestion>
    <suggestion>rheo-</suggestion>
    <suggestion>Re</suggestion>
    <suggestion>r</suggestion>
    <suggestion>Rh</suggestion>
</entry_list>

我认为因为您使用的密钥是临时的,所以有限的节点和属性可用 现在您可以根据您的要求操作此数据