从谷歌搜索建议解析xml结果时出现异常

时间:2018-06-10 11:01:53

标签: c# search xml-parsing

尝试获取Google建议。我m getting the XML back but when parsing using XDocument I收到以下异常:"根级别的数据无效。"。我无法弄清楚造成它的原因。

私人const字符串_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();

1 个答案:

答案 0 :(得分:1)

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

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

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