Xml使用NSURL委托方法进行解析

时间:2013-07-16 03:33:17

标签: iphone ios xml-parsing

请建议我使用连接方法进行xml解析的良好链接。

为什么需要连接方法?

这里我遇到了扩展课程的教程?

我不明白为什么需要延长它? 给我一些很好的例子,用连接

进行xml解析
#import "WebRequestAPI.h"

@interface NSObject(Extended)
-(void)setData:(NSString *)message items:(NSMutableArray *)items withtag:(int)tag;
@end

@interface ConnectionClass:NSObject{
NSMutableData *receivedData;
NSString *className;
NSString *rootName;
NSObject *m_delegate;
int tag;
}
-(id)initWithClass:(NSString *)class withRoot:(NSString *)root withDelegate:(NSObject *)delegate withTag:(int)t;
@end

@implementation ConnectionClass
-(id)initWithClass:(NSString *)class withRoot:(NSString *)root withDelegate:(NSObject *)delegate withTag:(int)t
{
     m_delegate = delegate;
     className = class;
     rootName = root;
     tag=t;
     return self;
}
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {
   if (receivedData != nil) {
      [receivedData appendData:data];
   } else {
      receivedData = [[NSMutableData alloc] initWithData:data];
  }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    if([className length]==0) {
        NSMutableArray *item = [[NSMutableArray alloc]       initWithObjects:rootName,receivedData,nil];
        [m_delegate setData:@"" items:item withtag:tag];
        [item release];
    }
    else {

         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
         NSString *strData = [[NSString alloc]  initWithBytes:[receivedData bytes]
                                                  length:[receivedData length] encoding: NSUTF8StringEncoding];
         NSData *data = [strData dataUsingEncoding:NSUTF8StringEncoding];
         XMLParser *xmlParser = [[XMLParser alloc] initWithData:data];
         [xmlParser setClassName:className withRootName:rootName];
         [xmlParser setDelegate:xmlParser];
         [xmlParser setShouldProcessNamespaces:NO];
         [xmlParser setShouldReportNamespacePrefixes:NO];
         [xmlParser setShouldResolveExternalEntities:NO];
         [xmlParser parse];
         [m_delegate setData:xmlParser.message items:xmlParser.items withtag:tag];
         [xmlParser release];
         [strData release];
         [pool release];
   }
}

-(void)dealloc {
    [receivedData release];
    [super dealloc];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
      [m_delegate setData:@"Connection required." items:nil withtag:0];
}

 @end

 @implementation WebRequestAPI

 -(id) init {

      return  self;
  }

   #pragma mark - demoAPI.
   + (void)demoApi:(NSObject *)delegate
   {
           int tag = 1;
           NSString *demoStr = [NSString stringWithFormat:@"http://www.astrology.com/horoscopes/daily-horoscope.rss"];
           demoStr = [demoStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; // NSASCIIStringEncoding];

           NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:demoStr]
                                                          cachePolicy:NSURLRequestReloadIgnoringCacheData                                                          timeoutInterval:60.0];

            ConnectionClass *con = [[[ConnectionClass alloc]initWithClass:@"item" withRoot:@"" withDelegate:delegate withTag:tag]autorelease];

           [[[NSURLConnection alloc]initWithRequest:theRequest delegate:con] autorelease];
}

 @end

1 个答案:

答案 0 :(得分:0)

http://www.sitepoint.com/parsing-xml-files-with-objective-c/

你可以调查一下这个。我觉得理解基础知识很好。掌握在手中:)

在我的viewcontroller.m

- (void)xmBtnTouched:(id)sender {
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://www.w3schools.com/xml/cd_catalog.xml"] cachePolicy:NSURLCacheStorageAllowed timeoutInterval:120.0f];
    NSLog(@"request is %@",request);
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];

}
/*******************************************************************************/
#pragma mark - connection delegates

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
    NSLog(@"received Data is %@",receivedData);

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

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Received data in finsh loading are %@",receivedData);
    receivedString = [[NSMutableString alloc]initWithData:receivedData encoding:NSASCIIStringEncoding];
    NSLog(@"received string is %@",receivedString);


    // setting tghe parser and common class for parser
    xmlParser = [[NSXMLParser alloc]initWithData:receivedData];
    parser = [[catalogParser alloc]init];
   [parser setStringInXml:receivedString];
    [parser setDelegate:self];
    [xmlParser setDelegate:parser];
    [xmlParser parse];


}

xmlparser.m

#import "catalogParser.h"

@implementation catalogParser
@synthesize stringInXml;
@synthesize catalogString;
@synthesize catalogArray;
@synthesize delegate;

- (id)initWithData:(NSData *)parseData {

    self = [super init];

    if (self) {



    }

    return self;

}
/**************************************************************************************/

#pragma mark - Xml parser delegates

- (void)parserDidStartDocument:(NSXMLParser *)parser
{
    NSLog(@"string i s%@",stringInXml);
    catalogArray = [[NSMutableArray alloc]init];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if ([elementName isEqualToString:@"CATALOG"]) {



    }
    if ([elementName isEqualToString:@"CD"]) {

        catalogObject = [[Catalog alloc]init];
    }

}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{

    NSLog(@"string is ********** %@",string);
    if(!catalogString)
    {
    catalogString = [[NSMutableString alloc]init];
    }

    catalogString = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
//    if ([elementName isEqualToString:@"CATALOG"]) {
//        return;
//    }
    if ([elementName isEqualToString:@"TITLE"]) {
        catalogObject.title = catalogString;
    }
    else if ([elementName isEqualToString:@"ARTIST"])
    {
        catalogObject.artist = catalogString;
    }
    else if ([elementName isEqualToString:@"COUNTRY"])
    {
        catalogObject.country = catalogString;
    }
    else if ([elementName isEqualToString:@"COMPANY"])
    {
        catalogObject.company = catalogString;
    }
    else if ([elementName isEqualToString:@"PRICE"])
    {
        catalogObject.price = catalogString;
    }
    else if ([elementName isEqualToString:@"YEAR"])
    {
        catalogObject.year = catalogString;
    }
else if ([elementName isEqualToString:@"CD"])
{
    [catalogArray addObject:catalogObject];
    [catalogObject release];
    catalogObject = nil;
     [catalogString release];
    catalogString = nil;
}


}
// sent when the parser begins parsing of the document.
- (void)parserDidEndDocument:(NSXMLParser *)parser
{

    [self.delegate parsingComplete:catalogArray];

}

在模态类catalog.h中

#import <Foundation/Foundation.h>

@interface Catalog : NSObject
@property(retain,nonatomic)NSString *title;
@property(retain,nonatomic)NSString *artist;
@property(retain,nonatomic)NSString *country;
@property(retain,nonatomic)NSString *company;
@property(retain,nonatomic)NSString *price;
@property(retain,nonatomic)NSString *year;

@end

在我的viewcontroller.m中 我有一个按钮,当被触摸时将调用连接代表然后获取数据,然后将其传递给xmlparser.m,其中我将相应的数据存储在模态类委托中,然后使用自定义委托我将此数据传递回视图控制器