Skip to main content

XML to NSDictionary

Hi here is the code for all the NSDictionary lovers

Use the following code to make XML_Dictionary.

Just make the classes from given code & use few steps of code
like : NSDictionary *_dictData= [XML_Dictionary dictionaryForXMLString:xmlString error:&error];

here we go with, Please give ur Value Feedback

//
//  XML_Dictionary.h
//  XML_Dictionary
//
//  Created by Vensan on 05/05/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface XML_Dictionary : NSObject<NSXMLParserDelegate>
{
    NSMutableDictionary *MainDictionary;
    NSMutableArray *dictArray;
    BOOL foundString;
}
@property(strong)NSString *stringValue;
- (NSDictionary *)objectWithData:(NSData *)data;
+ (NSDictionary *)dictionaryForXMLData:(NSData *)data error:(NSError **)errorPointer;
+ (NSDictionary *)dictionaryForXMLString:(NSString *)string error:(NSError **)errorPointer;
@end



//
//  XML_Dictionary.m
//  XML_Dictionary
//
//  Created by Vensan on 05/05/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "XML_Dictionary.h"

@implementation XML_Dictionary

@synthesize stringValue;
+ (NSDictionary *)dictionaryForXMLData:(NSData *)data error:(NSError **)error
{
    XML_Dictionary *reader = [[XML_Dictionary alloc]init];
    NSDictionary *rootDictionary = [reader objectWithData:data];
    return rootDictionary;
}
+ (NSDictionary *)dictionaryForXMLString:(NSString *)string error:(NSError **)error
{
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    return [XML_Dictionary dictionaryForXMLData:data error:error];
}
- (NSDictionary *)objectWithData:(NSData *)data
{
    MainDictionary=[[NSMutableDictionary alloc]init];
    dictArray=[[NSMutableArray alloc]init];
    // Parse the XML
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
    parser.delegate = self;
    BOOL success = [parser parse];
    
    // Return the stack's root dictionary on success
    if (success)
    {
        return (NSDictionary*)[dictArray objectAtIndex:0];
    }
    NSLog(@"Parsning failed");
    return nil;
}
#pragma mark -
#pragma mark NSXMLParserDelegate methods
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
    [dictArray addObject:MainDictionary];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    NSMutableDictionary *_newDict=[NSMutableDictionary dictionary];
    [dictArray addObject:_newDict];
    [_newDict addEntriesFromDictionary:attributeDict];
}
-(void)addToExistingParent:(NSMutableDictionary*)parentDict refArrayObject:(NSMutableArray*)referenceObject withElement:(NSString*)elementName withObject:(NSMutableArray*)Objects
{
    for (int i=0; i< [Objects count]; i++) 
    {
        [referenceObject addObject:[Objects objectAtIndex:i]];
    }
    [parentDict setObject:referenceObject forKey:elementName];
}
-(void)checkForElement:(NSString*)elementName inDictionary:(NSMutableDictionary*)parentDict withObject:(id)Objects
{
    if ([[parentDict objectForKey:elementName] isKindOfClass:[NSMutableArray class]]) 
    {
        NSMutableArray *referenceObject=[parentDict objectForKey:elementName];
        [self addToExistingParent:parentDict refArrayObject:referenceObject withElement:elementName withObject:[[NSMutableArray alloc]initWithObjects:Objects, nil]];
    }
    else 
    {
        NSString *existObject=[parentDict objectForKey:elementName];
        NSMutableArray *newDictArray=[NSMutableArray array];
        [self addToExistingParent:parentDict refArrayObject:newDictArray withElement:elementName withObject:[[NSMutableArray alloc]initWithObjects:existObject,Objects, nil]];
    }
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if (foundString
    {
        NSDictionary *attributes;
        if ([[[dictArray lastObject] allKeys] count]) 
        {
            attributes=[dictArray lastObject];
        }
        [dictArray removeLastObject];
        NSMutableDictionary *parentDict=[dictArray lastObject];
        if ([parentDict objectForKey:elementName])
        {
            [self checkForElement:elementName inDictionary:parentDict withObject:self.stringValue];
            
        }
        else 
        {
             [parentDict setObject:self.stringValue forKey:elementName];
        }
        if (attributes) 
        {
            [self checkForElement:elementName inDictionary:parentDict withObject:attributes];
            
        }
        foundString =FALSE;
    }
    else 
    {
        NSMutableDictionary *_lastDict=[dictArray lastObject];
        if ([[_lastDict allKeys] count]) 
        {
            [dictArray removeLastObject];
            NSMutableDictionary *parentDict=[dictArray lastObject];
            if ([parentDict objectForKey:elementName]) 
            {
                if ([[parentDict objectForKey:elementName] isKindOfClass:[NSMutableArray class]]) 
                {
                    NSMutableArray *referenceObject=[parentDict objectForKey:elementName];
                    [self addToExistingParent:parentDict refArrayObject:referenceObject withElement:elementName withObject:[[NSMutableArray alloc]initWithObjects:_lastDict, nil]];
                }
                else if ([[parentDict objectForKey:elementName] isKindOfClass:[NSMutableDictionary class]])
                {
                    NSMutableDictionary *existDict=[parentDict objectForKey:elementName];
                    NSMutableArray *newDictArray=[NSMutableArray array];
                    [self addToExistingParent:parentDict refArrayObject:newDictArray withElement:elementName withObject:[[NSMutableArray alloc]initWithObjects:existDict,_lastDict, nil]];
                }
            }
            else 
            {
                [parentDict setObject:_lastDict forKey:elementName];
            }
        }
        else 
        {
            [dictArray removeLastObject];
             NSMutableDictionary *parentDict=[dictArray lastObject];
            [parentDict setObject:@"" forKey:elementName];
        }
    }
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    self.stringValue=string;
    foundString=TRUE;
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
    NSLog(@"Parsing error==%@",[parseError localizedDescription]);
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
   
}
@end



Comments

  1. your code stopped in
    -(void)checkForElement:(NSString*)elementName inDictionary:(NSMutableDictionary*)parentDict withObject:(id)Objects

    Thread 1: EXC_BAD_ACCESS

    Plz reply...

    ReplyDelete
    Replies
    1. can i have look at xml string you r using?

      Delete
    2. Plz check it, file is here.. I put the string in this file for you...

      https://drive.google.com/file/d/0B_-J1zyZVVLoQzI0NW1rQ1VELVU/edit?usp=sharing

      Delete
    3. I just checked ur XML it worked fine in giving result, only thing i suggest is to use xml as single string. here is the code is used
      NSError *error = Nil;
      NSString *xmlString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"b.XML" ofType:@""] encoding:NSUTF8StringEncoding error:&error];
      if (!error) {
      NSDictionary *xmlDict = [XML_Dictionary dictionaryForXMLString:xmlString error:&error];

      if (error) {
      NSLog(@"error == %@", error.debugDescription);
      }
      NSLog(@"Dict == %@",xmlDict);
      }

      Happy coding... :)

      Delete
    4. I appreciate your attempt to help.
      I am facing same problem.. Can u plz give me any simple project of it? It will helps me lot. my email mamunruetcse@gmail.com

      Delete
    5. Thank you brother. Thank you lots. I got your project.. Trying to figure out the problem...

      Delete

Post a Comment

Popular posts from this blog