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

How I Reduced the Size of My React Native App by 85%

How and Why You Should Do It I borrowed 25$ from my friend to start a Play Store Developer account to put up my first app. I had already created the app, created the assets and published it in the store. Nobody wants to download a todo list app that costs 25mb of bandwidth and another 25 MB of storage space. So today I am going to share with you how I reduced the size of Tet from 25 MB to around 3.5 MB. Size Matters Like any beginner, I wrote my app using Expo, the awesome React Native platform that makes creating native apps a breeze. There is no native setup, you write javascript and Expo builds the binaries for you. I love everything about Expo except the size of the binaries. Each binary weighs around 25 MB regardless of your app. So the first thing I did was to migrate my existing Expo app to React Native. Migrating to React Native react-native init  a new project with the same name Copy the  source  files over from Expo project Install all de...

How to recover data of your Android KeyStore?

These methods can save you by recovering Key Alias and Key Password and KeyStore Password. This dialog becomes trouble to you? You should always keep the keystore file safe as you will not be able to update your previously uploaded APKs on PlayStore. It always need same keystore file for every version releases. But it’s even worse when you have KeyStore file and you forget any credentials shown in above box. But Good thing is you can recover them with certain tricks [Yes, there are always ways]. So let’s get straight to those ways. 1. Check your log files → For  windows  users, Go to windows file explorer C://Users/your PC name/.AndroidStudio1.4 ( your android studio version )\system\log\idea.log.1 ( or any old log number ) Open your log file in Notepad++ or Any text editor, and search for: android.injected.signing and if you are lucky enough then you will start seeing these. Pandroid.injected.signing.store.file = This is  file path where t...

React Native - Text Input

In this chapter, we will show you how to work with  TextInput  elements in React Native. The Home component will import and render inputs. App.js import React from 'react' ; import Inputs from './inputs.js' const App = () => { return ( < Inputs /> ) } export default App Inputs We will define the initial state. After defining the initial state, we will create the  handleEmail  and the  handlePassword  functions. These functions are used for updating state. The  login()  function will just alert the current value of the state. We will also add some other properties to text inputs to disable auto capitalisation, remove the bottom border on Android devices and set a placeholder. inputs.js import React , { Component } from 'react' import { View , Text , TouchableOpacity , TextInput , StyleSheet } from 'react-native' class Inputs extends Component { state = { ...