Search Posts in my Blog

Monday 11 July 2011

XML Parsing Example


XMLdemoAppDelegate.h

#import <UIKit/UIKit.h>

@interface XMLdemoAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
IBOutlet UINavigationController *nvc;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property(nonatomic,retain) IBOutlet UINavigationController *nvc;
@end


XMLdemoAppDelegate.m

#import "XMLdemoAppDelegate.h"

@implementation XMLdemoAppDelegate

@synthesize window;
@synthesize nvc;

#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    
    // Override point for customization after application launch.
[window addSubview:nvc.view];
[window makeKeyAndVisible];
return YES;
}

- (void)dealloc {
    [window release];
[nvc release];
    [super dealloc];
}


@end


XMLParser.h

#import <Foundation/Foundation.h>
@class XMLclass;

@interface XMLParser : NSObject <NSXMLParserDelegate>{

XMLclass *obj_XMLclass;
NSXMLParser *parser;
NSMutableString *currentnodeContent;
NSMutableArray *xmlobjectArray;
//NSMutableArray *arr
}

@property(nonatomic,retain) NSMutableArray *xmlobjectArray;
@end


XMLParser.m

#import "XMLParser.h"
#import "XMLclass.h"

@implementation XMLParser
@synthesize xmlobjectArray;


-(id)init
{
xmlobjectArray = [[NSMutableArray alloc]init];

NSString *str = [[NSBundle mainBundle] pathForResource:@"Demo" ofType:@"xml"];
parser = [[NSXMLParser alloc] initWithData:[NSData dataWithContentsOfFile:str]];
parser.delegate = self;
[parser parse];
return self;
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    NSString * errorString = [NSString stringWithFormat:@"Unable to download story feed from web site (Error code %i )", [parseError code]];
    NSLog(@"error parsing XML: %@", errorString);
    UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error loading content" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [errorAlert show];
}


- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict;
{

if ([elementName isEqualToString:@"CATALOG"]) {
currentnodeContent = [[NSMutableString alloc]init];
}else if ([elementName isEqualToString:@"BOOK"]) {
obj_XMLclass = [[XMLclass alloc]init];
}
}


- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName;
{
// sent when an end tag is encountered. The various parameters are supplied as above.
if ([elementName isEqualToString:@"BookName"]) {
obj_XMLclass.BookName = currentnodeContent;
}
else if ([elementName isEqualToString:@"BookPrice"]) {
obj_XMLclass.BookPrice = currentnodeContent;
}
else if ([elementName isEqualToString:@"BookAuthor"]) {
obj_XMLclass.BookAuthor = currentnodeContent;
}
else if ([elementName isEqualToString:@"BOOK"])
{
[xmlobjectArray addObject:obj_XMLclass];
[obj_XMLclass release];
obj_XMLclass = nil;
}
[currentnodeContent release];
currentnodeContent = nil;
currentnodeContent = [[NSMutableString alloc]init];
}


- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string;
{
[currentnodeContent appendString:string];

// This returns the string of the characters encountered thus far. You may not necessarily get the longest character run. The parser reserves the right to hand these to the delegate as potentially many calls in a row to -parser:foundCharacters:
}
@end



XMLclass.h

#import <Foundation/Foundation.h>

@interface XMLclass : NSObject {
NSString *BookName;
NSString *BookPrice;
NSString *BookAuthor;
}

@property(nonatomic,retain) NSString *BookName;
@property(nonatomic,retain) NSString *BookPrice;
@property(nonatomic,retain) NSString *BookAuthor;
@end


XMLclass.m

#import "XMLclass.h"

@implementation XMLclass
@synthesize BookName;
@synthesize BookPrice;
@synthesize BookAuthor;

@end


TableView.h

#import <UIKit/UIKit.h>
@class XMLParser;

@interface TableView : UITableViewController {

XMLParser *objXMLParser;
}

@end


TableView.m

#import "TableView.h"
#import "XMLParser.h"
#import "XMLclass.h"

@implementation TableView

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
objXMLParser =[[XMLParser alloc]init];
int a = [objXMLParser.xmlobjectArray count];
XMLclass *class=[objXMLParser.xmlobjectArray objectAtIndex:2];
NSLog(@"Bookname : %@",class.BookName);
NSLog(@"xmlobjectArray count : %d",a);

    [super viewDidLoad];
}


// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return YES;//(interfaceOrientation == UIInterfaceOrientationPortrait);
}



#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [objXMLParser.xmlobjectArray count] ;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
    XMLclass *a = [[XMLclass alloc]init];
a = [objXMLParser.xmlobjectArray objectAtIndex:indexPath.row];
cell.textLabel.text = a.BookAuthor;
//cell.detailTextLabel.text = a.BookPrice;
    return cell;
}



#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
*/
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end




Demo.xml ----> copy this below xml code in textedit and save it with .xml format. Add this file to your project.


<CATALOG>
<BOOK >
<BookName>Rahul First Book</BookName>
<BookPrice>5000         
</BookPrice>
<BookAuthor>Rahul Varma</BookAuthor>
</BOOK >
<BOOK >
<BookName>Priyankas First Book</BookName>
<BookPrice>4000</BookPrice>
<BookAuthor>Priyanka</BookAuthor>
</BOOK >
<BOOK >
<BookName>Vikrams First Book</BookName>
<BookPrice>20</BookPrice>
<BookAuthor>Vikram</BookAuthor>
</BOOK>
<BOOK >
<BookName>ABC's First Book</BookName>
<BookPrice>20</BookPrice>
<BookAuthor>ABC</BookAuthor>
</BOOK>
<BOOK >
<BookName>XYZ's First Book</BookName>
<BookPrice>20</BookPrice>
<BookAuthor>XYZ</BookAuthor>
</BOOK>
</CATALOG>



Output:

NOTE : The TableView only prints the Author's name from the .xml file
You can display more details by editing in TableView.m file in 'cellForRowAtIndexPath' function.


Build and Run the project.