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

问题描述 投票:0回答:1

试图获得Google建议。 Im 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个回答
1
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.