Skip to content

Instantly share code, notes, and snippets.

@orklann
Forked from jeffkreeftmeijer/XmlParser.h
Created May 5, 2021 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orklann/df1ec843a0468721a97a5b0f53969097 to your computer and use it in GitHub Desktop.
Save orklann/df1ec843a0468721a97a5b0f53969097 to your computer and use it in GitHub Desktop.
Objective-C XML parser
#import <Foundation/Foundation.h>
@interface XmlParser : NSObject <NSXMLParserDelegate>
@property (strong, nonatomic) NSData *xmlData;
@property (strong, nonatomic) NSMutableDictionary *dictionary;
@property (strong, nonatomic) NSMutableDictionary *currentNode;
@property (strong, nonatomic) NSMutableDictionary *currentParentNode;
- (id)initWithXMLData:(NSData *)xmlData;
- (NSMutableDictionary *)dictionary;
@end
#import "XmlParser.h"
@implementation XmlParser
@synthesize xmlData = _xmlData, dictionary = _dictionary, currentNode = _currentNode, currentParentNode = _currentParentNode;
- (id)initWithXMLData:(NSData *)xmlData
{
if(self = [super init]){
_xmlData = xmlData;
}
return self;
}
- (NSMutableDictionary *)dictionary
{
if(!_dictionary){
_dictionary = [[NSMutableDictionary alloc] init];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:self.xmlData];
parser.delegate = self;
[parser parse];
}
return _dictionary;
}
- (NSMutableDictionary *)currentNode
{
if(!_currentNode){
_currentNode = _dictionary;
}
return _currentNode;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSMutableDictionary *node = [[NSMutableDictionary alloc] init];
[self.currentNode setObject:node forKey:elementName];
self.currentParentNode = self.currentNode;
self.currentNode = node;
if([attributeDict count] != 0)
{
[self.currentNode setObject:attributeDict forKey:@"attributes"];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
self.currentNode = self.currentParentNode;
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
NSString *trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if([trimmedString length] != 0){
[self.currentNode setObject:trimmedString forKey:@"value"];
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment