문제

I run an XML parser that will come across something like <tag></tag> or <tag>content</tag>. Either way it stores the node content for later use.

Somewhere else down the line I want to check if the content was empty. I thought an empty node would be @"" or even (null), however neither of those are correct.

I would like to be able to determine what NSString represents the empty nodes. NSLogging the NSString results in some kind of newline, however checking it against @"\n" and @"\r" reveals it isn't either of those.

So is there some way to log the actual characters, escape sequences included, of an NSString? As in something like NSLog(@"\n"); would output "\n" instead of a new line.

도움이 되었습니까?

해결책

One (dirty?) trick that comes into my mind is to use the fact that NSJSONSerialization escapes all control and other non-ASCII characters:

NSString *foo = @"a\nb\rc d\t e\001\002";

NSData *json = [NSJSONSerialization dataWithJSONObject:@[foo] options:0 error:NULL];
NSString *escaped = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
NSLog(@"%@", escaped);

Output:

["a\nb\rc d\t e\u0001\u0002"]

다른 팁

Martin gave you an example of what you could do to log the characters. Or you could store it in a NSData and see it in hex:

NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", data);

Or, if you just want to see the control characters in XML hex, but leave printable characters unchanged, you can use CFStringTransform:

NSMutableString *mutableString = [string mutableCopy];
CFStringTransform((__bridge CFMutableStringRef)mutableString, NULL, kCFStringTransformToXMLHex, NO);

But in answer to the question about what the parser stores when it encounters <tag></tag>, it all depends upon how you implemented it (and show us what you did if you have questions). But most of us would alloc and init the NSMutableString in didStartElement, we'd append string in foundCharacters, and then store it in our model in didEndElement. In that scenario, that empty tag would yield a zero length mutable string (e.g. @"", except a mutable string). How did you conclude it was not @""? If you checked for [string isEqualToString:@""], that should have worked fine.

By the way, if you want to trim extra whitespace from your result, you could, in didEndElement, do something like:

self.modelObject.someStringProperty = [self.parsedString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

That way, if there were any extra spaces or newline characters, they'd get stripped out.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top