forked from piersoft/Acqualta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NSString_stripHtml.m
63 lines (53 loc) · 2.03 KB
/
NSString_stripHtml.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// NSString_stripHtml.m
// Copyright 2011 Leigh McCulloch. Released under the MIT license.
#import "NSString_stripHtml.h"
@interface NSString_stripHtml_XMLParsee : NSObject<NSXMLParserDelegate> {
@private
NSMutableArray* strings;
}
- (NSString*)getCharsFound;
@end
@implementation NSString_stripHtml_XMLParsee
- (id)init {
if((self = [super init])) {
strings = [[NSMutableArray alloc] init];
}
return self;
}
- (void)dealloc {
[strings release];
[super dealloc];
}
- (void)parser:(NSXMLParser*)parser foundCharacters:(NSString*)string {
[strings addObject:string];
}
- (NSString*)getCharsFound {
return [strings componentsJoinedByString:@""];
}
@end
@implementation NSString (stripHtml)
- (NSString*)stripHtml {
// take this string obj and wrap it in a root element to ensure only a single root element exists
NSString* string = [NSString stringWithFormat:@"<root>%@</root>", self];
// add the string to the xml parser
NSStringEncoding encoding = string.fastestEncoding;
NSData* data = [string dataUsingEncoding:encoding];
NSXMLParser* parser = [[NSXMLParser alloc] initWithData:data];
// parse the content keeping track of any chars found outside tags (this will be the stripped content)
NSString_stripHtml_XMLParsee* parsee = [[NSString_stripHtml_XMLParsee alloc] init];
parser.delegate = parsee;
[parser parse];
// log any errors encountered while parsing
//NSError * error = nil;
//if((error = [parser parserError])) {
// NSLog(@"This is a warning only. There was an error parsing the string to strip HTML. This error may be because the string did not contain valid XML, however the result will likely have been decoded correctly anyway.: %@", error);
//}
// any chars found while parsing are the stripped content
NSString* strippedString = [parsee getCharsFound];
// clean up
[parser release];
[parsee release];
// get the raw text out of the parsee after parsing, and return it
return strippedString;
}
@end