Skip to content

Instantly share code, notes, and snippets.

@xdream86
Last active December 29, 2015 17:19
Show Gist options
  • Save xdream86/7702963 to your computer and use it in GitHub Desktop.
Save xdream86/7702963 to your computer and use it in GitHub Desktop.
xml非法字符过滤
#import "NSString+XMLInvalidateCharactersEscaper.h"
#import <objc/runtime.h>
static void *CustomObjectKey;
@implementation NSString (XMLInvalidateCharactersEscaper)
/*
* category中使用property的示例
*/
///////////////////////////////////////////////////////////////////////////////////////////////////
- (NSDictionary *)escapeCharacterLUT {
NSDictionary *result = objc_getAssociatedObject(self, &CustomObjectKey);
if (!result) {
result = @{@"<" : @"&lt;",
@">" : @"&gt;",
@"&" : @"&amp;",
@"'" : @"&apos;",
@"\"" : @"&quot;"};
objc_setAssociatedObject(self, &CustomObjectKey, result, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return result;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setEscapeCharacterLUT:(id)newObject {
objc_setAssociatedObject(self, CustomObjectKey, newObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (NSString *)escapeInvalideCharactersInXML {
return [self escapeInvalideCharacterWithRegex:[[self.escapeCharacterLUT allKeys] componentsJoinedByString:@"|"]];
}
/**
* 将匹配实例中的非法字符过滤掉
*/
///////////////////////////////////////////////////////////////////////////////////////////////////
- (NSString *)escapeInvalideCharacterWithRegex:(NSString *)patten{
NSError* error = NULL;
NSMutableString *mutableString = [self mutableCopy];
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:patten
options:NSRegularExpressionCaseInsensitive
error:&error];
NSInteger offset = 0;
for (NSTextCheckingResult* result in [regex matchesInString:mutableString options:0 range:NSMakeRange(0, [self length])]) {
NSRange resultRange = [result rangeAtIndex:0];
resultRange.location += offset;
NSString* matchString = [mutableString substringWithRange:resultRange];
NSString* replacement = self.escapeCharacterLUT[matchString];
[mutableString replaceCharactersInRange:resultRange withString:replacement];
offset += ([replacement length] - [matchString length]);
}
return [mutableString copy];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment