NSXMLParser Simple Example

TJA picture TJA · Feb 15, 2014 · Viewed 15.9k times · Source

Most of the examples of how to invoke the NSXMLParser are contained within complex projects involving Apps. What does a simple example that demonstrates the callbacks look like.

Answer

TJA picture TJA · Dec 26, 2014

As part of exploring the NSXMLParser I created the following really simple code.

main.m

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        NSLog(@"Main Started");

        NSError *error = nil;

        // Load the file and check the result
        NSData *data = [NSData dataWithContentsOfFile:@"/Users/Tim/Documents/MusicXml/Small.xml"
                                          options:NSDataReadingUncached
                                            error:&error];
        if(error) {
            NSLog(@"Error %@", error);

            return 1;
        }


        // Create a parser and point it at the NSData object containing the file we just loaded
        NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];

        // Create an instance of our parser delegate and assign it to the parser
        MyXmlParserDelegate *parserDelegate = [[MyXmlParserDelegate alloc] init];
        [parser setDelegate:parserDelegate];

        // Invoke the parser and check the result
        [parser parse];
        error = [parser parserError];
        if(error)
        {
            NSLog(@"Error %@", error);

            return 1;
        }

        // All done
        NSLog(@"Main Ended");
    }
    return 0;
}

MyXmlParserDelegate.h

#import <Foundation/Foundation.h>

@interface MyXmlParserDelegate : NSObject <NSXMLParserDelegate>

@end

MyXmlParserDelegate.m

#import "MyXmlParserDelegate.h"

@implementation MyXmlParserDelegate

- (void) parserDidStartDocument:(NSXMLParser *)parser {
    NSLog(@"parserDidStartDocument");
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
    NSLog(@"didStartElement --> %@", elementName);
}

-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    NSLog(@"foundCharacters --> %@", string);
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    NSLog(@"didEndElement   --> %@", elementName);
}

- (void) parserDidEndDocument:(NSXMLParser *)parser {
    NSLog(@"parserDidEndDocument");
}
@end

I've posted it in the hope that it helps someone else.