0

请建议我使用连接方法进行 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
4

1 回答 1

0

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

你可以调查一下。我觉得了解基础知识很好。在你手中休息:)

在我的视图controller.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,在其中我将相应的数据存储在模态类委托中,然后使用我传递的自定义委托将此数据返回给视图控制器

于 2013-07-16T03:43:38.483 回答