XML PARSER……

XMLConverter.h

/**

* @class      XMLConverter XMLConverter.h “XMLConverter.h”

* @brief      XMLConverter

* @details    XMLConverter.h in XMLConverter

* @date       10/8/13

* @copyright  Copyright (c) 2013 Ruslan Soldatenko. All rights reserved.

*/

#import <Foundation/Foundation.h>

@interface XMLConverter : NSObject

/**

* The block called when XML-data convert finished

* @param[in] success YES – when XML-data convert successful, otherwise – NO.

* @param[in] dictionary Contains convert XML-data when success, otherwise – nil.

* @param[in] error Contains error of processing XML-data if exist, otherwise – nil.

*/

typedef void (^OutputBlock)(BOOL success, NSMutableDictionary *dictionary, NSError *error);

/**

*Convert XML data containing in input NSString object .

*@param[in] string Contains an NSString object with XML-data in the string format.

*@param[in] completion A block of code will be executed when the processing of XML-data is completed.

*This parameter must not be NULL.

*/

+ (void)convertXMLString:(NSString *)string completion:(OutputBlock)completion;

/**

*Convert XML data containing in input file.

*@param[in] filePath Contains an NSString object with absolute path to file with XML-data.

*@param[in] completion A block of code will be executed when the processing of XML-data is completed.

*This parameter must not be NULL.

*/

+ (void)convertXMLFile:(NSString *)filePath completion:(OutputBlock)completion;

/**

*Convert XML data containing in input NSData object.

*@param[in] data Contains NSData object with encapsulated XML contents.

*@param[in] completion A block of code will be executed when the processing of XML-data is completed.

*This parameter must not be NULL.

*/

+ (void)convertXMLData:(NSData *)data completion:(OutputBlock)completion;

/**

*Convert XML content referenced by the given URL.

*@param[in] url Contains an NSURL object specifying a URL.

*@param[in] completion A block of code will be executed when the processing of XML-data is completed.

*This parameter must not be NULL.

*/

+ (void)convertXMLURL:(NSURL *)url completion:(OutputBlock)completion;

/**

*Convert XML content from the specified stream.

*@param[in] stream Contains the specified input stream in NSInputStream object.

*@param[in] completion A block of code will be executed when the processing of XML-data is completed.

*This parameter must not be NULL.

*/

+ (void)convertXMLStream:(NSInputStream *)stream completion:(OutputBlock)completion;

@end

XMLConverter.m

/**

* @class      XMLConverter XMLConverter.m “XMLConverter.m”

* @brief      XMLConverter

* @details    XMLConverter.m in XMLConverter

* @date       10/8/13

* @copyright  Copyright (c) 2013 Ruslan Soldatenko. All rights reserved.

*/

#import “XMLConverter.h”

#define TEXT_NODE_KEY           @“#text”

#define ATTRIBUTE_PREFIX        @“-“

#define AXIS_PARENT            _axisAncestorOrSelf[_currentLevel – 1]

#define AXIS_PRECEDING_SIBLING _axisAncestorOrSelf[_currentLevel – 1][elementName]

#define AXIS_SELF              _axisAncestorOrSelf[_currentLevel]

@interface XMLConverter () <NSXMLParserDelegate>

@property (strong, nonatomic) NSMutableArray *axisAncestorOrSelf;

@property (strong, nonatomic) NSMutableString *selfText;

@property (strong, nonatomic) NSMutableDictionary *root;

@property (assign, nonatomic) NSError *error;

@property (assign, nonatomic) NSInteger currentLevel;

@end

@implementation XMLConverter

#pragma mark – Main Public Methods

+ (void)convertXMLData:(NSData *)data completion:(OutputBlock)completion

{

  ///Wrapper for -initWithData: method of NSXMLParser

  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];

    [[XMLConverter new] parser:parser completion:completion];

  });

}

+ (void)convertXMLURL:(NSURL *)url completion:(OutputBlock)completion

{

  ///Wrapper for -initWithContentsOfURL: method of NSXMLParser

  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];

    [[XMLConverter new] parser:parser completion:completion];

  });

}

+ (void)convertXMLStream:(NSInputStream *)stream completion:(OutputBlock)completion

{

  ///Wrapper for -initWithStream: method of NSXMLParser

  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    NSXMLParser *parser = [[NSXMLParser alloc] initWithStream:stream];

    [[XMLConverter new] parser:parser completion:completion];

  });

}

#pragma mark – Additional Public Methods

+ (void)convertXMLString:(NSString *)string completion:(OutputBlock)completion

{

  //Convert input string to NSData.

  NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];

  //Use class method for NSData.

  [self convertXMLData:data completion:completion];

}

+ (void)convertXMLFile:(NSString *)filePath completion:(OutputBlock)completion

{

  //Convert input file to NSData

  NSData* data = [NSData dataWithContentsOfFile:filePath];

  //Use class method for NSData.

  [self convertXMLData:data completion:completion];

}

#pragma mark – Internal methods

– (void)parser:(NSXMLParser *)parser completion:(OutputBlock)completion

{

  ///Completion of the parser to work and run the parser.

  [parser setDelegate: self];

  //Start parsing

  BOOL success = [parser parse];

  //execute output block with results of parsing as synchronous

  dispatch_sync(dispatch_get_main_queue(), ^{

    completion(success, _root, _error);

  });

}

– (void)dealloc

{

  ///Clear out all objects

  [_axisAncestorOrSelf removeAllObjects];

  _axisAncestorOrSelf = nil;

  _selfText = nil;

  _root = nil;

}

#pragma mark – NSXMLParserDelegate Handling XML

– (void)parserDidStartDocument:(NSXMLParser *)parser

{

  ///Initialize internal objects and values

  //Set counter for current level to root element level.

  _currentLevel = 0;

  //Create storage for parsing elements.

  _axisAncestorOrSelf = [NSMutableArray new];

  //Create object for result of parsing – the root object

  _root = [NSMutableDictionary new];

  //Put in the array as first the root object.

  [_axisAncestorOrSelf addObject:_root];

  //Create object for storing current element text value.

  _selfText = [NSMutableString new];

}

– (void)parserDidEndDocument:(NSXMLParser *)parser

{

  ///Clear unused object

  [_axisAncestorOrSelf removeLastObject];

}

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

{

  ///Start processing of the current element

  _currentLevel++;

  if ([_axisAncestorOrSelf count] == _currentLevel)

  {

    //Add dictionary for started element if it not exist.

    [_axisAncestorOrSelf addObject:[NSMutableDictionary new]];

    //Processing a text value (if it exist) of the previous (parent) element.

    if ([_selfText length] > 0)

    {

      [AXIS_PARENT setObject:_selfText forKey:TEXT_NODE_KEY];

      _selfText = [NSMutableString new];

    }

  }

  //Add attribute values (if it exist) to current element.

  if ([attributeDict count] != 0)

  {

    for (id key in [attributeDict allKeys])

    {

      NSString *attributeKey = [NSString stringWithFormat:@”%@%@”, ATTRIBUTE_PREFIX, key];

      [AXIS_SELF setObject:attributeDict[key] forKey:attributeKey];

    }

  }

}

– (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string

{

  ///Processing the text value of the current element

  NSCharacterSet *characterSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];

  NSString *text = [string stringByTrimmingCharactersInSet: characterSet];

  [_selfText appendString:text];

}

– (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName

{

  ///Completion processing of the current element

  if ([AXIS_SELF count] == 0)

  {

    //If exist only text value of element – set it as element value.

    [AXIS_PARENT setObject:_selfText forKey:elementName];

    _selfText = [NSMutableString new];

  }

  else

  {

    if ([_selfText length] > 0)

    {

      //If exist text value of element and child elements – set it as child element value.

      [AXIS_SELF setObject:_selfText forKey:TEXT_NODE_KEY];

      _selfText = [NSMutableString new];

    }

    if (AXIS_PRECEDING_SIBLING)

    {

      if ([AXIS_PRECEDING_SIBLING isKindOfClass:[NSMutableArray class]])

      {

        //If exist collection of preceding-sibling elements – add current element to collection.

        [AXIS_PRECEDING_SIBLING addObject:AXIS_SELF];

      }

      else if ([AXIS_PRECEDING_SIBLING isKindOfClass:[NSMutableDictionary class]])

      {

        /*

         If exist only one preceding-sibling element – create collection

         and add both (preceding-sibling and current) elements to collection.

         */

        NSMutableArray *elementsArray = [NSMutableArray new];

        [elementsArray addObjectsFromArray:@[AXIS_PRECEDING_SIBLING, AXIS_SELF]];

        [AXIS_PARENT setObject:elementsArray forKey:elementName];

      }

    }

    else

    {

      //If preceding-sibling elements not exist – add current element as child element.

      [AXIS_PARENT setObject:AXIS_SELF forKey:elementName];

    }

    //Remove current element from storage for parsing elements.

    [_axisAncestorOrSelf removeObject:AXIS_SELF];

  }

  _currentLevel–;

}

#pragma mark – NSXMLParserDelegate Handling XML Errors

– (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError

{

  ///Handle parse error

  //Output in the console error.

  NSLog(@”Line:%i Column:%i – Parse Error Occurred: %@”, [parser lineNumber], [parser columnNumber], [parseError description]);

  //Set error prorerty pointer to parse error.

  _error = parseError;

}

– (void)parser:(NSXMLParser *)parser validationErrorOccurred:(NSError *)validationError

{

  ///Handle validation error

  //Output in the console error.

  NSLog(@”Line:%i Column:%i – Validation Error Occurred: %@”, [parser lineNumber], [parser columnNumber], [validationError description]);

  //Set error prorerty pointer to validation error.

  _error = validationError;

}

@end

======================================================

//

//  AppDelegate.h

//  ContactsTestApp

#import <UIKit/UIKit.h>

@class ViewController1;

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) ViewController1 *viewController;

@end

AppDelegate.m

#import “AppDelegate.h”

#import “ViewController1.h”

@implementation AppDelegate

@synthesize window = _window;

@synthesize viewController = _viewController;

– (void)dealloc

{

    [_window release];

    [_viewController release];

    [super dealloc];

}

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

    // Override point for customization after application launch.

   // self.viewController = [[[ViewController alloc] initWithNibName:@”ViewController” bundle:nil] autorelease];

    

      self.viewController = [[[ViewController1 alloc] initWithNibName:@”ViewController1″ bundle:nil] autorelease];

    

    self.window.rootViewController = self.viewController;

    [self.window makeKeyAndVisible];

    return YES;

}

– (void)applicationWillResignActive:(UIApplication *)application

{

    /*

     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

     */

}

– (void)applicationDidEnterBackground:(UIApplication *)application

{

    /*

     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.

     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

     */

}

– (void)applicationWillEnterForeground:(UIApplication *)application

{

    /*

     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.

     */

}

– (void)applicationDidBecomeActive:(UIApplication *)application

{

    /*

     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

     */

}

– (void)applicationWillTerminate:(UIApplication *)application

{

    /*

     Called when the application is about to terminate.

     Save data if appropriate.

     See also applicationDidEnterBackground:.

     */

}

@end

ViewController1.h

#import <UIKit/UIKit.h>

@interface ViewController1 : UIViewController

{

    NSMutableArray *array;

    IBOutlet UITableView *table;

}

@end

ViewController1.m

#import “ViewController1.h”

#import “XMLConverter.h”

@interface ViewController1 ()

@end

@implementation ViewController1

– (void)viewDidLoad {

    [super viewDidLoad];

    

    array = [[NSMutableArray alloc] init];

    

    NSURL *url = [NSURL URLWithString:@”http://www.sandwell.gov.uk/rss/news&#8221;];

    [XMLConverter convertXMLURL:url completion:^(BOOL success, NSDictionary *dictionary, NSError *error) {

        NSLog(@”%@”,dictionary);

        array = [[[dictionary objectForKey:@”rss”] objectForKey:@”channel”] objectForKey:@”item”];

        [table reloadData];

        

    }];

    

    // Do any additional setup after loading the view from its nib.

}

#pragma mark – UITableViewDataSource And UITableViewDelegate

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return array.count;

}

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

    

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@”MyIdentifier”];

    

   

    if (cell == nil) {

        

       

        

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@”MyIdentifier”] autorelease];

        

        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        

        cell.textLabel.text =[[array objectAtIndex:indexPath.row] valueForKey:@”title”];

        

    }

  

    cell.textLabel.text = [[array objectAtIndex:indexPath.row] valueForKey:@”title”];

    return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

   

    

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

/*

@end

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s