NSXMLParser parsing xml file encoded using Windows

2019-05-10 07:01发布

问题:

i want to parse rss file in Windows-1256" encoding but it is not being read by parser i done alot of parsing in UTF8 encoding but only this don't work why?

rss file with Windows-1256

Solved solution is

NSString *myStr = [[NSString alloc] initWithData:myData encoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingWindowsArabic) ];
myStr = [myStr stringByReplacingOccurrencesOfString:@"encoding=\"windows-1251\"" withString:@""];        
NSData* aData = [myStr dataUsingEncoding:NSUTF8StringEncoding];    
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:aData];

回答1:

Thank you Mohamed for the answer I kept working on it for 10 days and we found no answers at all. This is my code:

-(void)parseXMLFileAtURL:(NSString *)URL {

NSURL *xmlURL = [NSURL URLWithString:URL];
NSData * dataXml = [[NSData alloc] initWithContentsOfURL:xmlURL];
NSString *myStr = [[NSString alloc] initWithData:dataXml encoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingWindowsArabic)];

myStr = [myStr stringByReplacingOccurrencesOfString:@"encoding=\"windows-1256\"" withString:@""];
NSData *aData = [myStr dataUsingEncoding:NSUTF8StringEncoding];

NSXMLParser *rssParser = [[NSXMLParser alloc] initWithData:aData];
[dataXml release];
[rssParser setDelegate:self];
[rssParser setShouldProcessNamespaces:NO];
[rssParser setShouldReportNamespacePrefixes:NO];
[rssParser setShouldResolveExternalEntities:NO];
[rssParser parse];
[rssParser setDelegate:nil];
[rssParser release];

}



回答2:

Also you can try this:

int length = str.length >100 ? 100:str.length;
NSString*mystr= [str stringByReplacingOccurrencesOfString:@"encoding=\".*?\"" 
                    withString:@""
                    options:NSRegularExpressionSearch 
                    range:NSMakeRange(0, length)];


回答3:

If you implement the parseErrorOccurred: method in your NSXMLParser delegate, it will give you the exact reason for the errors.

Something like:

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    NSLog(@"NSXMLParser ERROR: %@ - %@", , [parseError localizedDescription], [parseError localizedFailureReason]);
}