Reputation: 1065
I have an XML parser and i want to trim whitespace and new lines before it goes to the app delegate. I know it only works with string, but how to do it for the elements inside the object. More important is it smart to do this or is it better to do a separate trimming
newString =[menu.enable stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Upvotes: 0
Views: 541
Reputation: 13346
I've had my run ins with this issue myself, and it's not trivial. SriPriya's solution works but only if there are no newlines in the element content. This:
<foo>
hello
hi
</foo>
would (IIRC) come out as
@"hello\n hi"
when trimmed that way.
The solution I came up with to solve this (and there may be more elegant solutions out there - I'm all ears) is the following:
Presuming you're using NSXMLParser with a delegate class that handles the actual parsing (as in SriPriya's example above), where the -parser:foundCharacters:
method is located, you would do:
- (NSString *)removeNewlinesAndTabulation:(NSString *)fromString appending:(BOOL)appending
{
NSArray *a = [fromString componentsSeparatedByString:@"\n"];
NSMutableString *res = [NSMutableString stringWithString:appending ? @" " : @""];
for (NSString *s in a) {
s = [s stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (s.length > 0
&& res.length > (appending ? 1 : 0)) [res appendString:@" "];
[res appendString:s];
}
return res;
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if (! currentElementValue) {
currentElementValue = [[NSMutableString alloc] initWithString:[self removeNewlinesAndTabulation:string appending:NO]];
} else {
[currentElementValue appendString:[self removeNewlinesAndTabulation:string appending:currentElementValue.length > 0]];
}
}
I know it looks like a lot of code for something this simple, but it will correctly turn
<foo>
hi there all
i am typing some
stuff
</foo>
into
@"hi there all i am typing some stuff"
which sounds like what you're looking for.
Upvotes: 1
Reputation: 1240
In
- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
NSString *trimmedValue=[currentElementValue stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//NSLog(@"current value:%@",currentElementValue);
[aFile setValue:trimmedValue forKey:elementName];
}
it will trim every element before saving it to an object. Here, aFile is object
Upvotes: 3