我的NSXMLParsing由于“&”字符而无法工作。下面的代码是我的代码。有什么帮助吗?
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];
}
替换
NSString *str = [[NSString alloc] initWithData:downloadedData encoding:NSASCIIStringEncoding];
//NSString *contentString = [str stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
NSData * data=[str dataUsingEncoding:NSUTF8StringEncoding];
使用:
NSString *str = [[NSString alloc] initWithData:downloadedData encoding:NSASCIIStringEncoding];
NSString *contentString = [str stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
NSData * data=[contentString dataUsingEncoding:NSUTF8StringEncoding];
非常类似于sepehr-mahmoudian的答案,但是除了替换任何&之外,您还应该只替换未转义的&字符,为此,您可以使用正则表达式:
NSString *str = [[NSString alloc] initWithData:downloadedData encoding:NSASCIIStringEncoding];
//NSString *contentString = [str stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
NSData * data=[str dataUsingEncoding:NSUTF8StringEncoding];
使用:
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];
这是对我有用的东西:
NSString *response = [[NSString alloc]initWithData:dataResponse encoding:NSUTF8StringEncoding];
NSString *newResponse = [response stringByReplacingOccurrencesOfString:@"&:" withString:@"AND"];
NSData *dataObj = [newResponse dataUsingEncoding:NSUTF8StringEncoding];
如果我将其替换为符号'&',则响应将是正确的,但会引发解析错误:68。因此,我必须使用'and'。