-1

我正在尝试从 xml 文件中删除一个节点,一切正常,但有时会发生 xml 网页未加载的情况。这是我的代码:

private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        if (e.Error == null)
        {
            XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
            if (e.Error == null)
            {
                XDocument doc = XDocument.Parse(e.Result, LoadOptions.None);

                    var lyric = doc.Descendants(XName.Get("Lyric", "http://api.chartlyrics.com/")).FirstOrDefault();
                    TextBlock1.Text = lyric.Value;


            }

        }
    }

    private void btnLoad_Click(object sender, RoutedEventArgs e)
    {



        WebClient wc = new WebClient();
        wc.DownloadStringCompleted += HttpsCompleted;
        wc.DownloadStringAsync(new Uri("http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=michael%20jackson&song=bad));


    }

我已经阅读过使用 WebException 来处理这个“错误”,但我无法使用它。有人可以帮我吗?

4

1 回答 1

1

你试过这种方法吗?

    private void btnLoad_Click(object sender, RoutedEventArgs e)
    {
        try
        {

            WebClient wc = new WebClient();
            wc.DownloadStringCompleted += HttpsCompleted;
            wc.DownloadStringAsync(new Uri("http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=michael%20jackson&song=bad"));
        }
        catch (WebException ex)
        {
            // Check the exception here
        }
    }

并检查处理程序中的错误:

private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error == null)
    {
        XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
        if (e.Error == null)
        {
            XDocument doc = XDocument.Parse(e.Result, LoadOptions.None);

                var lyric = doc.Descendants(XName.Get("Lyric", "http://api.chartlyrics.com/")).FirstOrDefault();
                TextBlock1.Text = lyric.Value;
        }       
    }
    else
    {
        // Check for error here
    }
}

我意识到它有时会返回错误,我认为问题出在服务器上,因为如果我从网络浏览器访问它,我有时会得到结果,但很多时候我会出错。

于 2013-06-07T08:31:07.277 回答