NSXMLParser problem with “&”(Ampersand) character

2019-02-20 04:04发布

问题:

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

 NSString *myRequestString = [NSString stringWithFormat:@"http://abc.com/def/webservices/aa.php?family_id=%d",self.passFamilyId];
//NSLog(@"Requested Service = %@",myRequestString);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:myRequestString]];
[request setHTTPMethod: @"POST" ];
NSData *downloadedData = [ NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

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


//NSLog (@"string is :%@" ,str);    

NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];   

// Call the XMLParsers's initXMLParse method.
ClientDetailXmlParser *parser = (ClientDetailXmlParser*)[[ClientDetailXmlParser alloc] initXMLParser];
[xmlParser setDelegate:parser];
BOOL success = [xmlParser parse];

// Check for XML parsing.
if(success) 
{
    NSLog(@"No Errors in clientDetailXml.xml");     
}
else 
{
    NSLog(@"Error Error Error in clientDetailXml.xml!!!");
}   

[parser release];
parser = nil;

if (objClientAddUpdate != nil) {
    [objClientAddUpdate createBubbleList];
}

回答1:

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];


回答2:

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'.