views:

278

answers:

3

So NSXMLParser has problems parsing strings using the Windows-1252 encoder. Now I did find a solution on this page to convert it to NSUTF8StringEncoding. But now it bumps into characters it can't parse.

So I figured out that it will work if I would escape special characters and then transfer it back after parsing it. For example:

string = [string stringByReplacingOccurrencesOfString:@":" withString:@"__58__"];

Since it is allowed to use the _ character without getting a parser error and in NSXMLParser I can transfer the value back to it's proper character.

So is there a way I can loop through all ASCII character so I can replace all special characters (Except <, > and _ of course)?

A: 

Totally untested. I don't even know if it compiles, but it may get you on the right track. string needs to be an NSMutableString.

NSRange r = NSMakeRange(0, [string length]);
while (r.location < [string length])
{
  r = [string rangeOfCharactersFromSet:[NSCharacterSet symbolCharacterSet] options:0 range:r];
  if (r.location != NSNotFound)
  {
    NSMutableString *replacement = [[NSMutableString alloc] initWithCapacity:6];
    for (NSUInteger i = r.location; i <= NSMaxRange(r); i++)
    {
      unichar c = [string characterAtIndex:i];
      if (c != "_")
      {
        [replacement appendFormat:@"__%d__", (unsigned)c];
      }
    }
    [string replaceCharactersInRange:r withString:replacement];
    [replacement release]; replacement = nil;
    r.location = r.location + [string length] + 1;
    r.length = [string length] - r.location;
  }
}
Rob Napier
A: 

Assuming you have a NSMutableString str, you can do the following:

NSMutableString *str = ...;
[str replaceOccurrencesOfString:":" withString:@"__58__"
                        options:NSLiteralSearch
                          range:NSMakeRange(0, [str length])];
[str replaceOccurrencesOfString:"&" withString:@"__38__"
                        options:NSLiteralSearch
                          range:NSMakeRange(0, [str length])];

You see the pattern!

You can also just use XML entities for these values, e.g. replace & with &amp;.

notnoop
A: 

Thanks for the help everybody, this code actually solved my problem:

for (unichar asciiChar = 1; asciiChar <= 255; asciiChar++) {
 NSString *stringWithAsciiChar = [NSString stringWithCharacters:&asciiChar length:1];
 if (stringWithAsciiChar == nil) continue;
 string = [string stringByReplacingOccurrencesOfString:stringWithAsciiChar withString:[NSString stringWithFormat:@"__%d__", asciiChar]];
}