gpt4 book ai didi

iphone - 如何从服务器解析 XML 文件?

转载 作者:行者123 更新时间:2023-11-29 11:15:14 25 4
gpt4 key购买 nike

我已经搜索了很多,但教程和示例代码都没有帮助。我正在尝试解析一个非常简单的 XML 数据,只有一个结果总是相同的,xml 代码如下:

<Books>
<Book id="1">
<title>USERS ALREADY EXISTS</title>
</Book>
</Books>

那么,我如何使用 NSXMLParser 或您知道的其他方式解析这样的文件?

最佳答案

好吧,我解析 xml 的方式与其他人不同,坦率地说,我真的不知道它是哪种技术,但我向你保证它对我来说很好用,而且我已经在很多项目中成功实现了它。看看我的代码,我从一些 profile 加载推文。

This is the function where I make call for parser.

-(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];
}

}

And these are the NSURLConnection delegate methods:

- (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];
}

}

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

关于iphone - 如何从服务器解析 XML 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9747396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com