Skip to main content

How To Use XMLParser In Objective C

XMLParser

Step 1 Setup Environment

To create a new Xcode project select option Create a new Xcode project. It appears a Choose a template for your project dialog box as shown in given figure.

From the dialog box select Single View Application option and press next button.

The above screen contains number of fields:

   1.  Product Name

   2.  Organisation Name

   3.  Company Identifier

   4.  Bundle Identifier

   5.  Class Prefix

User has to provide basic information into specific field, which is very helpful to create a new project. Here, make sure that your Language must be Objective-C for this application project. Also it includes list of devices for which you want to develop application (iPhone/iPad). If you want to develop an application for both then simply select option Universal. After giving appropriate application name press next button.

Here, we gave XMLParsingDemo as Product Name. Now directory dialog box will appear. Select the directory for your new project from directory dialog box where exactly you want to save your application and select Create Button.

Step 2 List of main files of your project

List of main files of your project The main files are given below screen that is generated when you have created your application. By implementing code in following files you can perform various operations to the application.

Here, first we have to delete default ViewController from Main.storyboard and ViewController.h & ViewController.m file from the project navigation bar. (Right side bar).

Step 3 Create new Objective-C (.h & .m file) file in your project

Now, Right Click on Project XMLParsingDemo >> New File >> Cocoa Touch Class >> Next

Here, give class name DisplayTableViewController and must Select subclass for TableView in iOS is UITableViewController and Click Next. Now, store your file where you want to save and finally click on Create button.

Step 4 Create Objective-C (.h & .m file) file in your project

Now, click on Main.storyboard and Connect your DisplayTableViewController file to the TableViewController for that click TableViewController, open Utility window & choose Identity Inspector (3rd section from left).

Now, Select TableViewController cell and open Utility window for cell and choose Attributes Inspector(4th section from left).

Step 5 Code for .h file of TableView

Now, Write a Code below the comment section in DisplayTableViewController.h header file

For NSXMLParser method, first of all we will initialised NSXMLParserDelegate in .h file between ‘<’ & ‘>’symbol like:

@interface DisplayTableViewController : UITableViewController <NSXMLParserDelegate>

Now, make some property which we want to used during the parsing process in .h file using @property:
@property (nonatomic, strong) NSMutableDictionary *dictData;
 @property (nonatomic,strong) NSMutableArray *marrXMLData;
  @property (nonatomic,strong) NSMutableString *mstrXMLString;
        @property (nonatomic,strong) NSMutableDictionary *mdictXMLPart;

Step 6 Code for .m file of TableView

Now, Write a Code below the comment section in DisplayTableViewController.m implementation file,

1)  Synthesise property which we are created in .h file below the @implementation

     DisplayTableViewController line which looks like:

          @synthesize marrXMLData;
          @synthesize mstrXMLString;
          @synthesize mdictXMLPart;

2) Now, create a new function for XMLParsing with name startParsing using below code:

- (void)startParsing
{
}

Now, initialise NSXMLParser in this function , set parser delegate and start parsing with below code:

- (void)startParsing
{
  NSXMLParser *xmlparser = [[NSXMLParser alloc] initWithContentsOfURL:[NSURL                       URLWithString:@"http://images.apple.com/main/rss/hotnews/hotnews.rss#sthash.TyhRD7Zy.dpuf"]  ];
  [xmlparser setDelegate:self];
  [xmlparser parse];

      if (marrXMLData.count != 0)
        {
               [self.tableView reloadData];
        }
}

When [xmlparser parse]; line will get executed, NSXMLParserDelegate methods will work step by step, read whole XML data and store it into marrXMLData array. After reading full XML file, control again moves to [xmlparser parse]; line and execute code following that line which is used for reloading TableView data with marrXMLData array.

3) Now, implement NSXMLParserDelegate Method in .m file.

We write 3 methods of NSXMLParserDelegate which is given below:

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

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

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName;
{
}

Now, write code in all 3 methods step by step:

6.1 Code for didStartElement Method

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict;
{
       if ([elementName isEqualToString:@"rss"])
        {
            marrXMLData = [[NSMutableArray alloc] init];
        }
       if ([elementName isEqualToString:@"item"])
        {
            mdictXMLPart = [[NSMutableDictionary alloc] init];
        }
}

6.2 Code for foundCharacters Method

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string;
{
       if (!mstrXMLString)
        {
             mstrXMLString = [[NSMutableString alloc] initWithString:string];
  } else {
            [mstrXMLString appendString:string];
        }
}

6.3 Code for didEndElement Method

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName;
{
    if ([elementName isEqualToString:@"title"] || [elementName isEqualToString:@"pubDate"])
     {
          [mdictXMLPart setObject:mstrXMLString forKey:elementName];
     }
    if ([elementName isEqualToString:@"item"])
     {
         [marrXMLData addObject:mdictXMLPart];
     }
   mstrXMLString = nil;
}

Step 7 Display data in TableView

Now, we will get all XML data into our NSMutableArray. So, fill UITableView with that data , UITableViewDelegate & UITableViewDatasource method implemented accordingly and code for display that data given below:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
     return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
      return [marrXMLData count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"                                                                           forIndexPath:indexPath];

    cell.textLabel.text = [[[marrXMLData objectAtIndex:indexPath.row] valueForKey:@"title"]                      stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    cell.detailTextLabel.text = [[[marrXMLData objectAtIndex:indexPath.row]                                                valueForKey:@"pubDate" ] stringByTrimmingCharactersInSet:[NSCharacterSet                                  whitespaceAndNewlineCharacterSet]];

   return cell;
}

If you are not able to understand above TableView DataSource & Delegate then first read our blog named.

Step 8 Call NSXMLDelegate Method

Now, we must call startParsing function from viewDidLoad method to start parsing process.

So, viewDidLoad function looks like:

- (void)viewDidLoad
{
     [super viewDidLoad];
     [self startParsing];
}

Step 9 Build & Run Project

Now, build & run the project. For shortcut press cmd+b for build & cmd+r for run the project.

Wow, its build Successfully.

I hope you find this tutorial helpful. If you are facing any issues or have any questions regarding XMLParsing with NSXMLParser, please feel free to post a reply over here, I would be glad to help you.


Comments

Popular Posts

What are the Alternatives of device UDID in iOS? - iOS7 / iOS 6 / iOS 5 – Get Device Unique Identifier UDID

Get Device Unique Identifier UDID Following code will help you to get the unique-device-identifier known as UDID. No matter what iOS user is using, you can get the UDID of the current iOS device by following code. - ( NSString *)UDID { NSString *uuidString = nil ; // get os version NSUInteger currentOSVersion = [[[[[UIDevice currentDevice ] systemVersion ] componentsSeparatedByString: @" . " ] objectAtIndex: 0 ] integerValue ]; if (currentOSVersion <= 5 ) { if ([[ NSUserDefaults standardUserDefaults ] valueForKey: @" udid " ]) { uuidString = [[ NSUserDefaults standardDefaults ] valueForKey: @" udid " ]; } else { CFUUIDRef uuidRef = CFUUIDCreate ( kCFAllocatorDefault ); uuidString = ( NSString *) CFBridgingRelease ( CFUUIDCreateString ( NULL ,uuidRef)); CFRelease (uuidRef); [[ NSUserDefaults standardUserDefaults ] setObject: uuidString ForKey: @" udid " ]; [[ NSUserDefaults standardUserDefaults ] synchro...

16 AWS Gotchas

16 AWS Gotchas In January I launched the MVP for my own startup,  Proximistyle , which helps you find what you’re looking for nearby. On advice from friends and industry contacts I chose AWS as my cloud provider. Having never had to set up my own cloud infrastructure before, the learning curve to get from no experience to a stable VPC system I was happy with was significantly steeper than expected, and had its fair share of surprises. #1 Take advantage of the free resources offered AWS offers a free tier for new accounts. If you have recently bought a domain and set up a company you qualify for the free tier for a year. Additionally, if you are a bootstrapped startup you can apply for  the Startup Builders package  and get $1000 in AWS credits. After doing the above, you’re now ready to get started with setting up the AWS infrastructure for your startup. #2 Set up billing budgets and alerting The very first thing you should do after setting up billing, is enabling a budge...

Ultimate Folder Structure For Your React Native Project

  Ultimate Folder Structure For Your React Native Project React native project structure React Native is a flexible framework, giving developers the freedom to choose their code structure. However, this can be a double-edged sword for beginners. Though it offers ease of coding, it can soon become challenging to manage as your project expands. Thus, a structured folder system can be beneficial in many ways like better organization, simplified module management, adhering to coding practices, and giving a professional touch to your project. This write-up discusses a version of a folder arrangement that I employ in my React Native projects. This structure is based on best practices and can be modified to suit the specific needs of your project. Before we get into the project structure let’s give credit to @sanjay who has the original idea of the structure but I modify his version of the code, to make it better. Base library axios  — For network calling. react-navigation ...