尝试获取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();
答案 0 :(得分:1)
您正在尝试解析您的Uri,而不是发出请求并解析响应。
var response = await client.GetAsync(uri);
var result = await response.Content.ReadAsStringAsync();
您还应该重复使用HttpClient
个实例,即使它是一次性的。