【问题标题】:Exception when parsing xml results from google search suggestions解析来自谷歌搜索建议的 xml 结果时出现异常
【发布时间】:2018-06-10 11:01:52
【问题描述】:

尝试获取 Google 建议。我m getting the XML back but when parsing using XDocument Im 收到以下异常:“根级别的数据无效。”。我不知道是什么原因造成的。

private const string _suggestSearchUrl = "http://www.google.com/complete/search?output=toolbar&q={0}&hl=en";

    public List<GoogleSuggestion> GetData(string query)
    {
        if (String.IsNullOrWhiteSpace(query))
        {
            throw new ArgumentException("Argument cannot be null or empty!", "query");
        }

        string result = String.Empty;

        using (HttpClient client = new HttpClient())
        {
            result = String.Format(_suggestSearchUrl, query);
        }


        XDocument doc = XDocument.Parse(result);  (I`m getting exception here)





        var suggestions = from suggestion in doc.Descendants("CompleteSuggestion")
                          select new GoogleSuggestion
                          {
                              Phrase = suggestion.Element("suggestion").Attribute("data").Value
                          };

        return suggestions.ToList();

【问题讨论】:

    标签: c# search xml-parsing


    【解决方案1】:

    您正在尝试解析 Uri,而不是发出请求并解析响应。

    var response = await client.GetAsync(uri);
    var result = await response.Content.ReadAsStringAsync();
    

    您还应该重复使用您的 HttpClient 实例,即使它是一次性的。

    【讨论】:

    • Im having trouble when invoking the method, currently Im 传递我的查询字符串并等待方法完成但它永远在那里:Task> task = GetDataAsync("test");任务.Wait(); var x = task.Result;
    • 好吧,我找到了这个帖子:stackoverflow.com/questions/28601678/…
    • 将你的方法设为async Task&lt;List&lt;GoogleSuggestion&gt;&gt;,按照惯例重命名为Async,以便调用者知道等待它,并在调用者中await它。您可能还想在使用await 的任何地方使用ConfigureAwait(false),除非您确定要使用true,这是默认设置,但几乎不是您想要的。异步很强大,但有很多警告使它变得比它应该的更难。尽量避免.Result.Wait()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    相关资源
    最近更新 更多