Per iOS il seguente codice dovrebbe funzionare per i codici numerici. Dovrebbe essere relativamente facile da estendere a personaggi del calibro di &
...
-(NSString*)unescapeHtmlCodes:(NSString*)input {
NSRange rangeOfHTMLEntity = [input rangeOfString:@"&#"];
if(NSNotFound == rangeOfHTMLEntity.location) {
return input;
}
NSMutableString* answer = [[NSMutableString alloc] init];
[answer autorelease];
NSScanner* scanner = [NSScanner scannerWithString:input];
[scanner setCharactersToBeSkipped:nil]; // we want all white-space
while(![scanner isAtEnd]) {
NSString* fragment;
[scanner scanUpToString:@"&#" intoString:&fragment];
if(nil != fragment) { // e.g. '& B'
[answer appendString:fragment];
}
if(![scanner isAtEnd]) { // implicitly we scanned to the next '&#'
int scanLocation = (int)[scanner scanLocation];
[scanner setScanLocation:scanLocation+2]; // skip over '&#'
int htmlCode;
if([scanner scanInt:&htmlCode]) {
char c = htmlCode;
[answer appendFormat:@"%c", c];
scanLocation = (int)[scanner scanLocation];
[scanner setScanLocation:scanLocation+1]; // skip over ';'
} else {
// err ?
}
}
}
return answer;
}
Alcuni codice unità-test ...
-(void)testUnescapeHtmlCodes {
NSString* expected = @"A & B";
NSString* actual = [self unescapeHtmlCodes:@"A & B"];
STAssertTrue([expected isEqualToString:actual], @"actual = %@", actual);
expected = @"& B";
actual = [self unescapeHtmlCodes:@"& B"];
STAssertTrue([expected isEqualToString:actual], @"actual = %@", actual);
expected = @"A &";
actual = [self unescapeHtmlCodes:@"A &"];
STAssertTrue([expected isEqualToString:actual], @"actual = %@", actual);
}
fonte
2012-05-04 02:53:29
ho fatto lo stesso ... ma c'è un modo integrato per fai questo ... – nbojja
@nbojja Quanto più integrato vuoi? Se sei preoccupato, aggiungi un metodo che faccia questo come categoria su NSString e poi sia integrato. – Abizern
@Abizern: molte lingue hanno metodi incorporati per codificare e decodificare le entità HTML, Obj-C non ha questo e molti altri cose che i programmatori danno per scontato dal 2002. La ricerca e la sostituzione sono un cattivo sostituto, perché dovrai dedicare un po 'di tempo a sapere che ottieni tutte le entità. –