Pages

Tuesday, January 22, 2013

How to Load External XML in xCode

1. Create a different class for this. Lets suppose XMLParse

Code for XMLParse.h is:



#import <Foundation/Foundation.h>

@interface XMLParse : NSObject <NSXMLParserDelegate>
{
    NSMutableString *currentElementValue;
    NSMutableArray *users;
}
@property(nonatomic, retain) NSMutableArray *users;

- (XMLParse *) initXMLParser;
- (void) loadDataFromXML;
- (void) doParse:(NSData *)data;
@end


Code for XMLParse.m is:


#import "XMLParse.h"
@implementation XMLParse
@synthesize users;

- (XMLParse *) initXMLParser
{
    users = [[NSMutableArray alloc] init];
    return self;
}

//XMLParsing
-(void) loadDataFromXML
{
    NSString *path=[[NSBundle mainBundle] pathForResource:@"UserInfo" ofType:@"xml"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    [self doParse:data];
}

- (void) doParse:(NSData *)data
{
    NSXMLParser *nsXMLParse = [[NSXMLParser alloc] initWithData:data];
    [nsXMLParse setDelegate:self];
    [nsXMLParse parse];
}

-(void) parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qName
    attributes:(NSDictionary *)attributeDict
{
    printf("User Info %s", [elementName UTF8String]);
    
    if([elementName isEqualToString:@"User"])
    {
        //Get the attribute value
        printf("XML - %s", [[attributeDict objectForKey:@"uname"] UTF8String]);
    }
}

-(void) parser:(NSXMLParser *)parser
 didEndElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qName
{
    printf("\nEnd ");
    if ([elementName isEqualToString:@"Users"]) {
        // We reached the end of the XML document
        return;
    }
    if ([elementName isEqualToString:@"user"]) {
        
    } else {
        
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if (!currentElementValue) {
        // init the ad hoc string with the value
        currentElementValue = [[NSMutableString alloc] initWithString:string];
    } else {
        // append value to the ad hoc string
        [currentElementValue appendString:string];
    }
    printf("Processing value for : %s", [string UTF8String]);
}
@end



How to call 


#import "XMLParse.h"

@interface ViewController ()
@property (nonatomic) XMLParse *parser;
@end
@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.parser = [[XMLParse alloc] initXMLParser];
    [self.parser loadDataFromXML];
}