我想通过XML解析获取Google新闻数据并将其保存到数组中。 XML就像这样
http://news.google.co.in/news?pz=1&cf=all&ned=in&hl=en&output=rss
答案 0 :(得分: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];
}
}
我使用了一些字符串函数来分隔标记并将值存储在Array中。
答案 1 :(得分:0)
这是您可以开始的地方:NSXMLParser类引用。