Created
October 30, 2011 03:51
-
-
Save zwaldowski/1325443 to your computer and use it in GitHub Desktop.
Modern, simplified SMXMLDocument
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
The MIT License | |
Copyright (c) 2011 Spotlight Mobile | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in | |
all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
THE SOFTWARE. | |
*/ | |
// SMXMLDocument is a very handy lightweight XML parser for iOS. | |
extern NSString *const SMXMLDocumentErrorDomain; | |
@interface SMXMLElement : NSObject | |
@property (nonatomic, assign, readonly) SMXMLElement *parent; | |
@property (nonatomic, copy, readonly) NSString *name; | |
@property (nonatomic, readonly) NSString *value; | |
@property (nonatomic, readonly) NSArray *children; | |
@property (nonatomic, strong, readonly) NSDictionary *attributes; | |
@property (nonatomic, readonly) SMXMLElement *firstChild; | |
@property (nonatomic, readonly) SMXMLElement *lastChild; | |
+ (SMXMLElement *)rootElementForData:(NSData *)data; | |
+ (SMXMLElement *)rootElementForData:(NSData *)data error:(NSError **)error; | |
- (id)childrenWithValue:(NSString *)name forAttribute:(NSString *)value; | |
@end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "SMXMLDocument.h" | |
NSString *const SMXMLDocumentErrorDomain = @"SMXMLDocumentErrorDomain"; | |
static NSError *SMXMLDocumentError(NSXMLParser *parser, NSError *parseError) { | |
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:parseError forKey:NSUnderlyingErrorKey]; | |
NSNumber *lineNumber = [NSNumber numberWithInteger:parser.lineNumber]; | |
NSNumber *columnNumber = [NSNumber numberWithInteger:parser.columnNumber]; | |
[userInfo setObject:[NSString stringWithFormat:NSLocalizedString(@"Malformed XML document. Error at line %@:%@.", @""), lineNumber, columnNumber] forKey:NSLocalizedDescriptionKey]; | |
[userInfo setObject:lineNumber forKey:@"LineNumber"]; | |
[userInfo setObject:columnNumber forKey:@"ColumnNumber"]; | |
return [NSError errorWithDomain:SMXMLDocumentErrorDomain code:1 userInfo:userInfo]; | |
} | |
@interface SMXMLElement() <NSXMLParserDelegate> { | |
NSMutableString *value; | |
NSMutableArray *children; | |
} | |
@property (nonatomic, assign) SMXMLElement *root; | |
@property (nonatomic, assign, readwrite) SMXMLElement *parent; | |
@property (nonatomic, copy, readwrite) NSString *name; | |
@property (nonatomic, strong, readwrite) NSDictionary *attributes; | |
@property (nonatomic, strong) NSError *error; | |
@end | |
@implementation SMXMLElement | |
@synthesize parent, name, value, children, attributes, root, error; | |
+ (SMXMLElement *)rootElementForData:(NSData *)data { | |
return [self rootElementForData:data error:NULL]; | |
} | |
+ (SMXMLElement *)rootElementForData:(NSData *)data error:(NSError **)error { | |
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; | |
SMXMLElement *root = [SMXMLElement new]; | |
parser.delegate = root; | |
parser.shouldProcessNamespaces = YES; | |
parser.shouldReportNamespacePrefixes = YES; | |
parser.shouldResolveExternalEntities = NO; | |
BOOL success = [parser parse]; | |
if (!success) { | |
if (error) | |
*error = parser.parserError; | |
return nil; | |
} | |
return root; | |
} | |
- (NSString *)descriptionWithIndent:(NSString *)indent { | |
NSMutableString *s = [NSMutableString string]; | |
[s appendFormat:@"%@<%@", indent, name]; | |
[attributes enumerateKeysAndObjectsUsingBlock:^(NSString *attribute, id attribValue, BOOL *stop) { | |
[s appendFormat:@" %@=\"%@\"", attribute, attribValue]; | |
}]; | |
NSString *trimVal = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; | |
if (trimVal.length > 25) | |
trimVal = [NSString stringWithFormat:@"%@…", [trimVal substringToIndex:25]]; | |
if (children.count) { | |
[s appendString:@">\n"]; | |
NSString *childIndent = [indent stringByAppendingString:@" "]; | |
if (trimVal.length) | |
[s appendFormat:@"%@%@\n", childIndent, trimVal]; | |
for (SMXMLElement *child in children) | |
[s appendFormat:@"%@\n", [child descriptionWithIndent:childIndent]]; | |
[s appendFormat:@"%@</%@>", indent, name]; | |
} else if (trimVal.length) | |
[s appendFormat:@">%@</%@>", trimVal, name]; | |
else [s appendString:@"/>"]; | |
return s; | |
} | |
- (NSString *)description { | |
return [self descriptionWithIndent:@""]; | |
} | |
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { | |
if (value) | |
[value appendString:string]; | |
else | |
value = [string mutableCopy]; | |
} | |
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { | |
if (self.name || self.attributes) { | |
SMXMLElement *child = [SMXMLElement new]; | |
child.root = self.root ? self.root : self; | |
child.parent = self; | |
child.name = elementName; | |
child.attributes = attributeDict; | |
parser.delegate = child; | |
if (children) | |
[children addObject:child]; | |
else | |
children = [[NSMutableArray alloc] initWithObjects:child, nil]; | |
} else { | |
self.name = elementName; | |
self.attributes = attributeDict; | |
} | |
} | |
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { | |
parser.delegate = parent; | |
} | |
- (void)parserDidEndDocument:(NSXMLParser *)parser { | |
parser.delegate = nil; | |
} | |
- (id)valueForKey:(NSString *)key { | |
if ([key isEqualToString:@"@attributes"]) | |
return attributes; | |
NSIndexSet *indexes = [children indexesOfObjectsPassingTest:^BOOL(SMXMLElement *child, NSUInteger idx, BOOL *stop) { | |
return ([child.name isEqual:key]); | |
}]; | |
if (indexes.count == 1) { | |
SMXMLElement *element = [children objectAtIndex:[indexes firstIndex]]; | |
if (element.children.count) | |
return element; | |
else | |
return element.value; | |
} else { | |
NSArray *elements = [children objectsAtIndexes:indexes]; | |
return [elements valueForKey:key]; | |
} | |
return nil; | |
} | |
- (id)valueForKeyPath:(NSString *)keyPath { | |
NSRange attribRange = [keyPath rangeOfString:@"@attributes"]; | |
if (attribRange.location == NSNotFound) | |
return [super valueForKeyPath:keyPath]; | |
else { | |
NSString *newKeyPath = [keyPath substringToIndex:NSMaxRange(attribRange)]; | |
NSString *newDictKeyPath = [keyPath substringFromIndex:NSMaxRange(attribRange)]; | |
id result = [super valueForKeyPath:newKeyPath]; | |
return [result valueForKeyPath:newDictKeyPath]; | |
} | |
} | |
- (id)childrenWithValue:(NSString *)testName forAttribute:(NSString *)testValue { | |
NSString *keyPath = [NSString stringWithFormat:@"@attributes.%@", testValue]; | |
NSIndexSet *indexes = [children indexesOfObjectsPassingTest:^BOOL(SMXMLElement *child, NSUInteger idx, BOOL *stop) { | |
return [[child valueForKeyPath:keyPath] isEqualToString:testName]; | |
}]; | |
if (!indexes.count) | |
return nil; | |
if (indexes.count == 1) | |
return [children objectAtIndex:[indexes firstIndex]]; | |
else | |
return [children objectsAtIndexes:indexes]; | |
} | |
- (SMXMLElement *)firstChild { | |
return children.count ? [children objectAtIndex:0] : nil; | |
} | |
- (SMXMLElement *)lastChild { | |
return [children lastObject]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment