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

Reloading UITableView while Animating Scroll in iOS 11

Reloading UITableView while Animating Scroll Calling  reloadData  on  UITableView  may not be the most efficient way to update your cells, but sometimes it’s easier to ensure the data you are storing is in sync with what your  UITableView  is showing. In iOS 10  reloadData  could be called at any time and it would not affect the scrolling UI of  UITableView . However, in iOS 11 calling  reloadData  while your  UITableView  is animating scrolling causes the  UITableView  to stop its scroll animation and not complete. We noticed this is only true for scroll animations triggered via one of the  UITableView  methods (such as  scrollToRow(at:at:animated:) ) and not for scroll animations caused by user interaction. This can be an issue when server responses trigger a  reloadData  call since they can happen at any moment, possibly when scroll animation is occurring. Example of s...

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...

Xcode & Instruments: Measuring Launch time, CPU Usage, Memory Leaks, Energy Impact and Frame Rate

When you’re developing applications for modern mobile devices, it’s vital that you consider the performance footprint that it has on older devices and in less than ideal network conditions. Fortunately Apple provides several powerful tools that enable Engineers to measure, investigate and understand the different performance characteristics of an application running on an iOS device. Recently I spent some time with these tools working to better understand the performance characteristics of an eCommerce application and finding ways that we can optimise the experience for our users. We realised that applications that are increasingly performance intensive, consume excessive amounts of memory, drain battery life and feel uncomfortably slow are less likely to retain users. With the release of iOS 12.0 it’s easier than ever for users to find applications that are consuming the most of their device’s finite amount of resources. Users can now make informed decisions abou...