This repository has been archived by the owner on Jun 23, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathNSString_stripHtml.m
52 lines (43 loc) · 1.7 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
// 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)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
// and that any ampersands are escaped to preserve the escaped sequences
NSString* string = [self stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
string = [NSString stringWithFormat:@"<root>%@</root>", string];
// 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];
// any chars found while parsing are the stripped content
NSString* strippedString = [parsee getCharsFound];
// get the raw text out of the parsee after parsing, and return it
return strippedString;
}
@end