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

时间:2012-03-17 04:57:33

标签: iphone ios xml xml-parsing nsxmlparser

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

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

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

1 个答案:

答案 0 :(得分:2)

我解析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中。