C#和Forecast API

时间:2013-11-26 04:37:09

标签: c# api weather-api

我对API数据转发完全陌生,并希望得到一些帮助。这是我目前的代码:

else if (e.KeyCode == Keys.Enter & InputTextbox.Text.Contains("hot"))
{
    try
    {
        XElement doc = XElement.Load("https://api.forecast.io/forecast/*APIKEY*/-31.4296,152.9082");
        OutputTextbox.Text = "It is currently " + doc;                                                             
        pBuilder.ClearContent();                                                                                        
        pBuilder.AppendText(OutputTextbox.Text);                                                                        
        sSynth.Speak
        pBuilder);                                                                                                             
        e.SuppressKeyPress = true;                                                                                                          
        InputTextbox.Text = "";
    }
    catch (System.Xml.XmlException fe)
    {
        MessageBox.Show(fe.Message);
    }

这会返回错误消息:“根级别的数据无效。第1行,第1位。”

有人可以告诉我出错的地方吗?

1 个答案:

答案 0 :(得分:4)

首先,你需要看看api调用的输出是什么,试试:

using(var client = new WebClient()) {
    var responseStr = client.DownloadString("https://api.forecast.io/forecast/*APIKEY*/-31.4296,152.9082");
    OutputTextbox.Text = responseStr;
}

然后,要使用XElement加载此xml,它需要是完全有效的XML。这是您的错误消息的来源:XElement非常严格。如果回复是HTML,请考虑使用HtmlAgilityPack,这样可以节省您的理智。

var doc = new HtmlDocument();
doc.Load("https://....");

如果是json api或类似内容,请考虑使用ServiceStack。这也将拯救你的理智。

祝你好运。