Wednesday, 6 July 2011

XML parsing using NSXMLParser ( SAX Parser for iPhone )


In this post we will see on how to use NSXMLParser to parse an XML file present inside the project bundle but before that lets have a look on what is NSXMLparser and how does it parses an XMLFile
NSXMLParser: Instances of this class parsees XML documents (including DTD declarations) in an event-driven manner. Its an event based parser ( SAX parser). So NSXMLParser notifies its delegate about the items (elements, attributes, CDATA blocks, comments, and so on) that it encounters as it processes an XML document. It also reports parsing errors. For convenience, an NSXMLParser object in the following descriptions is sometimes referred to as a parser object.
Design Phase: This is the output that we will be getting when we parse the XML file, so for the design part you may see from the design that we have to take a UITableViewController and when we are done parsing the xml file, the XML data will be shown in the table.


Step 1: Open Xcode and create a windows based application and add a UITableVIewController subclass file to it with the name XMLTableViewController,. Add a new NSObject subclass file with the name Employee.
Note: The idea behing the Employee class is that we will be parsing the XML files and will be getting the records of the employees. We will allocate and initalise the employee objects from these records in the xml. This is always a better approach. We should never directly use the xml data. It should be clear to you if not now.
Step 2: The XML file that we are going to parse from the bundle looks like this
Select the XMLTableViewController.h file and declare the add the following code
#import <UIKit/UIKit.h>
#import "Employee.h"

@interface XMLTableViewController : UITableViewController {

         NSMutableArray * employees;
         Employee * emp_obj;
         NSXMLParser * Parser;
         NSMutableString * nodeContent;
}

@end
Code Explanation: In the above code you may see that I have declared the object of NSMutableArray class because when our parsing will be done we will be adding the parsed data inside this array and display the content of this array inside the table, The NSMutableString variable named nodeContent will get the data from the xml document and this data will be stored inside the properties of the NSObject subclass called as the Employee, the NSObject subclass is added because even in future if the xml file structure is altered and one new element is added then all you have to do is just add a property inside the Employee file and use the property to get the data from the nodeContent variable of the mutable string. Finally we have declared the object of the NSXMLParser class which will parse the xml file with the help of its delegate methods.
Code of the Employee.h file
@interface Employee : NSObject {

         NSString * emp_name;
         NSString * emp_city;
}
@property(nonatomic,retain) NSString * emp_name;
@property(nonatomic,retain) NSString * emp_city;
@end
Code  of the Employee.m file
#import "Employee.h"


@implementation Employee

@synthesize emp_name,emp_city;

@end

Step 3: Initialize every object inside the init method of the XMLTableView.m here’s the code
- (id)initWithStyle:(UITableViewStyle)style {


    if (self = [super initWithStyle:style]) {
            employees=[[NSMutableArray alloc]init];
            nodeContent=[[NSMutableString alloc]init];
            Parser=[NSXMLParser alloc];
            Parser.delegate=self;
            [self loadXML];
            [Parser parse];
    }
    return self;
}
Code Explanation: As you may see from the above code that the Parser which is an object of the NSXMLParser class has to parse an xml file but for doing that you have to supply in the location of the xml file which is present inside the bundle and once you have done that just call a method called parse of the NXMLParser which notifies the object of the NSXMLParser class to begin with the parsing and since the parsing is done with the help of the delegate method of the class we have specified the delegate of the Parser to self. Below given is the function which will just gives the location to of the XMLFIle to the NSXMLParser
-(void) loadXML
{
         NSData * data=[[NSData alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"XMLFile" ofType:@"xml"]];
         [Parser initWithData:data];
         [data release];
        
}
Step 4: The NSXMLParser has 3 delegate method called as
didStartElement: Sent by a parser object to its delegate when it encounters a start tag for an element.
foundCharacters: Sent by a parser object to provide its delegate with a string representing all or part of the characters of the current element.
didEndElement: Sent by a parser object to its delegate when it encounters an end tag for an element.
The above are the three method that are mostly used to parse the xml file of course there are some other methods as well you may use those methods as per your business logic
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
         if([elementName isEqualToString:@"emp"])
         {
            emp_obj=[[Employee alloc]init];
         }
        
}
Code Explanation: Here you specify the start tag of the xml element from where the parsing should actually begin.
Here’s the code of the foundCharacter

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
        
[nodeContent appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}

Code Explanation: here you append the data from the xml file to the mutable string variable
Here’s the code for the didEndElement
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
         if([elementName isEqualToString:@"name"])
         {
            emp_obj.emp_name=nodeContent;
         }
         else if([elementName isEqualToString:@"city"])
         {
            emp_obj.emp_city=nodeContent;
           
         }
         else if([elementName isEqualToString:@"emp"])
         {
            [employees addObject:emp_obj];
            [emp_obj release];
            emp_obj=nil;
        
         }
         [nodeContent release];
         nodeContent = nil;
         nodeContent = [[NSMutableString alloc]init];
        
        
}
 Code Explanation: Here you add the data from the xml file present inside the nodecontent to the properties that you have created inside the Employee and then add the object of the Employee class to the object of the mutable array. Once the data is inside the mutable array you may display the data present inside the mutable array in the table.
Check out the datasource methods of the table below
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [employees 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:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    
     Employee * emp = [employees objectAtIndex:indexPath.row];
     cell.textLabel.text=emp.emp_name;
     cell.detailTextLabel.text=emp.emp_city;
    return cell;
}

Step 5: after doing that select the AppDelegate.m file and create the object of the XMLTableViewController in applicationDidFinishLaunching method and run the application here’s the view at the final output.

Friday, 17 June 2011

XML Dom Parser for iPhone - GDataXML Parser


GDataXML is Google’s XML processing library. We have choosen GDataXML since it performs well for DOM parsers, supports both reading and writing, and is so easy to integrate. However, if you are using a different DOM parser, it should be almost exactly the same as this but just slightly different API calls.
Design Phase: For this sample application we will parse an XML file that is present in the bundle and display its content in the table view.
Before beginning with this tutorial you have to download the GData library from below link
Step 1: Open Xcode and select the windows based application template and add UITableViewController subclass file to it with the name MyTableViewController, after doing this their would be two files that would be added into your class group [MyTableViewController.h and MyTableViewController.m].
Step 2: Add the GData library into your project so for that select the downloaded GData file from the download folder and inside the folder you will find a folder with the name source and then inside the source folder you will find a folder named “XML support”, drag and drop this folder into your application. Make sure you add this by selecting the copy files into destination folder option.



Once this is done then we will have to do some settings so that GData library works nicely with our application.
Perform the settings that are given below:
1) Select the project tab from the xcode menu and select the edit project settings option



2) You will see a window in front of you that’s your project window from there select the header search path option (you can type header search path in the search bar) and type the following that is given in the image below









3) Once you are done with header search path the other setting that you have to do is set the other linker flag (you may type other linker flag in the search bar), now once you find the other linker flag just type the following data in the image given below








4) Now its time to test whether you have made the correct settings or not and for that you have to import the GDatatXMLNode header file in the  .h file of the MyTableViewController class and press build your application.

Step 3: Here’s a look at our XML file, which is present in the bundle, now in order to read this file just follow the steps given below



First in the .h file declare the following objects, I have used comments to describe the objects,
#import <UIKit/UIKit.h>
#import "GDataXMLNode.h"

@interface MyTableViewController: UITableViewController {

 //stores the entire data about the XML document
 GDataXMLDocument *xmlDocument;

 //string variable to hold the location of the XML File
 NSString *xmlFileLocation;

 //after parsing the data will be stored in the array
 NSMutableArray *data_from_xml;

 //stores the error information that occured
 NSError *error;
}
@end

Now into the .m file, select the init method and add this piece of code.

-(id)initWithStyle:(UITableViewStyle)style {
    if (self = [super initWithStyle:style]) {
  xmlFileLocation = [[NSBundle mainBundle]pathForResource:@"Cars" ofType:@"xml"];
  NSData *xmlData = [NSData dataWithContentsOfFile:xmlFileLocation];
  xmlDocument = [[GDataXMLDocument alloc]initWithData:xmlData options:0 error:&error];
   NSArray *getData = [[xmlDocument rootElement]elementsForName:@"car"];
  data_from_xml = [[NSMutableArray alloc]init];
  for(GDataXMLElement *e in getData)
  {
   [data_from_xml addObject:e];
  }
    }
    return self;
}

Step 4: Now once the above step is completed then just add the number of sections and rows for section in the datasource method of the table view, here’s a view of doing that
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [data_from_xml count];
}

Now its time to see some real GData
In the cell for row at index path method when you give title to each cells then in this case the titles will be coming from the XML file so for that what you have to do is select the appropriate elements from the XML file and display them in the table view and here’s how you do that
// 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:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    // Set up the cell...
 cell.textLabel.text = [[[[data_from_xml objectAtIndex:indexPath.row]elementsForName:@"company"]objectAtIndex:0]stringValue];
 cell.detailTextLabel.text = [[[[data_from_xml objectAtIndex:indexPath.row]elementsForName:@"model"]objectAtIndex:0]stringValue];
    
 return cell;
}

Step 5: Select the AppDelegate.m file and add the table view to the window.  Here is how you will do that.

#import "GDataAppAppDelegate.h"
#import "MyTableViewController.h"
@implementation GDataAppAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    // Override point for customization after application launch
 MyTableViewController * mtvc = [[MyTableViewController alloc]initWithStyle:UITableViewStyleGrouped];
 [window addSubview:mtvc.view];
    [window makeKeyAndVisible];
}
Click build and go you will see the output as given below


Summary
In this post, we have read the xml document using a dom parser. Now using GData you can also write an xml file to store your applications data. We will soon have a tutorial for that as well.

Custom TableView Cell


In this post we will have a look on how to create a custom cell for the table view. 
Design view: For this demo we will make a custom UITableViewCell with three labels and one image view, the three labels will represent details about a particular cartoon character including an image view which will show the image of that cartoon character. Here is a view at the final output.

Step 1: Open Xcode and select the windows based application template and add the UITableViewController subclass file to the project with the name MyTableViewController or any other name of your choice. Now there will be two files that would be added into your project those are the MyTableViewController.h and MyTableViewController.m file. Now add a UITableViewCell subclass file to your project with the name MyCustomCell and two more files will be added with the name MyCustomCell.h and MyCustomCell.m.



Step 2: Select the MyCustomCell.h file and declare three variables of UILabel type and one variable of UIImageView type. Also declare the properties of these variables that you will be using (we are declaring properties so that we can access these variables with the help of the dot operator in the MyTableViewController.m file). Here’s the code to do that.

#import <UIKit/UIKit.h>
@interface MyCustomCell: UITableViewCell {
 UILabel *charName,*cartoonName,*charCity;
 UIImageView *charImage;
}
@property (nonatomic,retain) UILabel *charName,*cartoonName,*charCity;
@property (nonatomic,retain) UIImageView *charImage;
@end

Step 3: In the MyCustomCell.m file give memory to these variables
#import " MyCustomCell.h"
@implementation MyCustomCell
@synthesize charCity,charName,charImage,cartoonName;

- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) {
        // Initialization code
    charName = [[UILabel alloc]initWithFrame:CGRectMake(102, 14, 85, 21)];
    charName.font = [UIFont fontWithName:@"Verdana" size:12.0f];
    
    cartoonName = [[UILabel alloc]initWithFrame:CGRectMake(102, 40, 111,21)];
    cartoonName.font = [UIFont fontWithName:@"Verdana" size:12.0f];
 
    charCity = [[UILabel alloc]initWithFrame:CGRectMake(102, 65, 81, 21)];
    charCity.font = [UIFont fontWithName:@"Verdana" size:12.0f];
 
charImage = [[UIImageView alloc]initWithFrame:CGRectMake(7, 12, 78, 70)];
 
  //adding the controls in the table cell
  [self.contentView addSubview:charName];
  [self.contentView addSubview:cartoonName];
  [self.contentView addSubview:charCity];
  [self.contentView addSubview:charImage];
 
    }
    return self;
}
Now after allocating memory to the variables and setting the frame of the lables and the imageView its time to add this custom cell to our table view so in order to do that first you have to import the MyCustomCell.h as the header in the MyTableViewController.h file

#import <UIKit/UIKit.h>
#import " MyCustomCell.h"

@interface MyTableViewController: UITableViewController {
}
@end

and then in the MyTableViewController.m file go to the

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {


Here all you have to do is replace the below code 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

With this code

 MyCustomCell *cell = (MyCustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[MyCustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }

and then using switch case manipulate the cells

switch (indexPath.row) {
 case 0:
  cell.cartoonName.text = @"Dragon ball z";
  cell.charName.text = @"Goku";
  cell.charCity.text= @"Japan";
  cell.charImage.image = [UIImage imageNamed:@"goku.jpg"];
  break;
 
 case 1:
  cell.cartoonName.text = @"Batman ";
  cell.charName.text = @"Bruce Wyane";
  cell.charCity.text= @"Gotham City";
  cell.charImage.image = [UIImage imageNamed:@"batman4952.jpg"];
  break;
 
 case 2:
  cell.cartoonName.text = @"Superman";
  cell.charName.text = @"Clark Kent";
  cell.charCity.text= @"Krypton";
  cell.charImage.image = [UIImage imageNamed:@"superman.jpg"];
  break;
 
 case 3:
  cell.cartoonName.text = @"Spider man";
  cell.charName.text = @"Peter Parker";
  cell.charCity.text= @"NewYork";
  cell.charImage.image = [UIImage imageNamed:@"Spider-Man.jpg"];
  break;
 
 case 4:
  cell.cartoonName.text = @"Iron Man";
  cell.charName.text = @"Tony Stark";
  cell.charCity.text= @"U.S.A";
  cell.charImage.image = [UIImage imageNamed:@"ironman.jpg"];
  break;

}
Step 4: The above code is self-explanatory.  By using switch case operator We are giving different names and images to different cells of the table view.
Note: for this demo we have to increase the row height of the cell. So implement the below delegate method of the UITableView.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
 return 90;
}

Step 5: Select the AppDelegate.m file of your project and add this piece of code and then run your application to get the output just like the above image

#import "CustomCelldemoAppDelegate.h"
#import "MyTableViewController.h"
@implementation CustomCelldemoAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(UIApplication *)application {    

    // Override point for customization after application launch
 MyTableViewController *mtVC = [[MyTableViewController alloc]init];
 [window addSubview:mtVC.view];

    [window makeKeyAndVisible];
}

After adding this select build and go and get the below output