NSXMLParser problem with “&”(Ampersand) character

后端 未结 3 1806
误落风尘
误落风尘 2021-01-16 09:14

My NSXMLParsing is not working because of \"&\" character.. my code s below .any help please ?

 NSString *myRequestString = [NSString stringWithFormat:@         


        
相关标签:
3条回答
  • 2021-01-16 09:44

    Replace

    NSString *str = [[NSString alloc] initWithData:downloadedData encoding:NSASCIIStringEncoding];
    //NSString *contentString = [str stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
    NSData * data=[str dataUsingEncoding:NSUTF8StringEncoding];
    

    With:

    NSString *str = [[NSString alloc] initWithData:downloadedData encoding:NSASCIIStringEncoding];
    NSString *contentString = [str stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
    NSData * data=[contentString dataUsingEncoding:NSUTF8StringEncoding];
    
    0 讨论(0)
  • 2021-01-16 09:45

    Very similar to sepehr-mahmoudian's answer, but instead of replace any & you should really just replace & characters that are unescaped, to do this you can use a regexp:

    NSString *str = [[NSString alloc] initWithData:downloadedData encoding:NSASCIIStringEncoding];
    //NSString *contentString = [str stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
    NSData * data=[str dataUsingEncoding:NSUTF8StringEncoding];
    

    With:

    NSString *str = [[NSString alloc] initWithData:downloadedData encoding:NSASCIIStringEncoding];
    
    NSRange searchedRange = NSMakeRange(0, [str length]);
    NSString *pattern = @"&(?!(#[0-9]{2,4}|[A-z]{2,6});)";
    NSError *error = nil;
    
    NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
    str = [regex stringByReplacingMatchesInString:str options:0 range:searchedRange withTemplate:@"&"];
    
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    0 讨论(0)
  • 2021-01-16 10:01

    Here's what worked for me:

    NSString *response = [[NSString alloc]initWithData:dataResponse encoding:NSUTF8StringEncoding];
    NSString *newResponse = [response stringByReplacingOccurrencesOfString:@"&amp:" withString:@"AND"];
    NSData *dataObj = [newResponse dataUsingEncoding:NSUTF8StringEncoding];
    

    If I replaced it with symbol '&', the response would be correct, but it would throw parsing error: 68. So I had to use 'and'.

    0 讨论(0)
提交回复
热议问题