如何通过XML解析从谷歌新闻获取数据。

3

请查看以下线程:https://dev59.com/xnA75IYBdhLWcg3wFEsI - Sunil Pandey
你尝试过搜索XML解析器吗?展示一些努力。每个人都会帮助你。 - rohan-patel
2个回答

1

我解析XML的方式与其他人不同,坦白地说,我真的不知道它是哪种技术,但我向您保证它对我很有效,并且我已经在许多项目中成功实现了它。请查看我的代码,其中我从某个profile加载推文。

这是我调用解析器的函数。

-(void)loadtweet
{
@try
{
    NSString *urlString = [NSString stringWithFormat:@"https://api.twitter.com/1/statuses/user_timeline.xml?screen_name=SrBachchan&count=5"];

    NSLog(@"fetching data from--------> : %@",urlString);

    NSString* escapedUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

    NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:escapedUrlString]];

    NSURLConnection *con=[[NSURLConnection alloc]  initWithRequest:request1 delegate:self];
    if(con)
        truckData=[[NSMutableData data]retain];
}

@catch (NSException *exception) 
{
    UIAlertView *v = [[UIAlertView alloc] initWithTitle:@"ERROR" message:@"Please Try Again Later." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [v show];
    [v release];
}

}

以下是NSURLConnection的委托方法:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[truckData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
[truckData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 

{
   [tweets removeAllObjects];
 @try 
{
    // [app.trucks removeAllObjects];
    NSString *thexml=[[NSString alloc] initWithBytes:[truckData mutableBytes] length:[truckData length] encoding:NSUTF8StringEncoding];

    NSArray *array=[thexml componentsSeparatedByString:@"<status>"];
    NSLog(@"%d",[array count]);

    for(int i=1;i<[array count];i++)
    {
        NSString *str=[array objectAtIndex:i];
        NSArray *arr1=[str componentsSeparatedByString:@"<text>"];
        NSString *data=[arr1 objectAtIndex:1];
        NSRange ranfrom=[data rangeOfString:@"</text>"];
        // nt.truckName=[data substringToIndex:ranfrom.location];
        [tweets  addObject:[data substringToIndex:ranfrom.location]];
    }
}

@catch (NSException *exception) 
{
    UIAlertView *v = [[UIAlertView alloc] initWithTitle:@"ERROR" message:@"Please Try Again Later." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [v show];
    [v release];
 }

}

我使用了一些字符串函数来分离标签,并将值存储在数组中。


请告诉我如果您有任何疑问。 - rohan-patel

0
这是你可以开始的地方:NSXMLParser 类参考文档。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接