如何以XML格式获取搜索结果

时间:2010-05-18 08:40:52

标签: iphone xml search

我打算制作一款iPhone搜索应用。用户键入搜索字符串。一些搜索引擎会搜索该字符串,如Google,Live,Yahoo ......

我需要以XML格式获取搜索结果。有没有办法做到这一点。需要帮助。请。

谢谢和问候, 世斌

2 个答案:

答案 0 :(得分:1)

有不同的Web服务API可用。我建议你使用它们。

Google搜索API: http://code.google.com/intl/sv-SE/apis/ajaxsearch/web.html

Google JS API经常返回JSON。但这也很容易合作。如果需要,您应该能够轻松地将JSON转换为XML。

答案 1 :(得分:1)

RESTful search request to Google AJAXJSON格式返回回复。 JSON就像是一个非常精简的XML版本。

Google不再使其SOAP接口可用,因此我不知道您是否能够从它们获取XML,至少通过公共接口。幸运的是,JSON响应对于请求和解析iPhone来说是微不足道的。

您可以使用ASIHTTPRequest发出请求,并使用json-framework在iPhone上解析JSON格式的回复。

例如,要创建并提交基于Google AJAX页面上示例的搜索请求,您可以使用ASIHTTPRequest的-requestWithURL-startSynchronous方法:

NSURL *searchURL = [NSURL URLWithString:@"http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Paris%20Hilton"];
ASIHTTPRequest *googleRequest = [ASIHTTPRequest requestWithURL:searchURL];
[googleRequest addRequestHeader:@"Referer" value:[self deviceIPAddress]]; 
[googleRequest startSynchronous];

您可以根据搜索字词构建NSURL实例,escaping请求参数。

如果我按照Google的示例,我还会在此网址中添加API密钥。 Google要求您使用API​​密钥进行REST搜索。您应该注册API密钥over here并将其添加到您的请求中。

您还应在请求标头中指定引用IP地址,在这种情况下,它将是iPhone的本地IP地址,例如:

- (NSString *) deviceIPAddress {
    char iphoneIP[255];
    strcpy(iphoneIP,"127.0.0.1"); // if everything fails
    NSHost *myHost = [NSHost currentHost];
    if (myHost) {
        NSString *address = [myHost address];    
        if (address)
            strcpy(iphoneIP, [address cStringUsingEncoding:NSUTF8StringEncoding]);
    }
    return [NSString stringWithFormat:@"%s",iphoneIP]; 
}

还有ASIHTTPRequest文档中详述的异步请求方法。您可以使用这些来阻止iPhone UI在搜索请求时被绑定。

无论如何,一旦掌握了Google的JSON格式响应,就可以使用json-framework SBJSON解析器对象将响应解析为NSDictionary对象:

NSError *requestError = [googleRequest error];
if (!requestError) {
    SBJSON *jsonParser = [[SBJSON alloc] init];
    NSString *googleResponse = [googleRequest responseString];
    NSDictionary *searchResults = [jsonParser objectWithString:googleResponse error:nil];
    [jsonParser release];
    // do stuff with searchResults...
}
相关问题