How can we parse an XML with ISO-8859-15 encoding?
I was using UTF开发者_Go百科-8 encoded xml for parsing using NSXMLParser. But some of the special characters were causing problems and so decided to use ISO-8859-15 encoding.
But after that the parser doesnt even start parsing and is giving the error 31 - NSXMLParserUnknownEncodingError. What should I do now? Is it possible by anyway we can parse a ISO-8859-15 encoded xml in iphone? Will libxml or anyother parser provide support for this encoding?
I solved this issue by myself. We decided to use the UTF-8 encoding for the xml and parsed it using the NSXMLParser. But before the parsing we did the following steps.
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://the url for parsing"]];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[[NSString alloc] initWithData:responseData encoding:NSISOLatin1StringEncoding] autorelease];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:[result dataUsingEncoding:NSUTF8StringEncoding]];
Then after that some italian characters(3-4) were still causing problems and we manually replaced them after getting the result.
Now everything works fine.
NSISOLatin1StringEncoding is wrong, e.g. € can't encode.
xml file:
<?xml version="1.0" encoding="ISO-8859-15"?>
...
xCode:
NSString *xmlFileAsString = nil; //read xml file
NSStringEncoding iso88599 = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingISOLatin9);
NSData *data = [xmlFileAsString dataUsingEncoding:iso88599 allowLossyConversion:YES];
xmlDocPtr doc = xmlReadMemory([data bytes], (int)[data length], NULL, NULL, XML_PARSE_COMPACT | XML_PARSE_NOBLANKS);
if (doc == NULL) {
...
get string from xml: (e.g. USAdditions.m)
+ (NSString *)stringWithXmlString:(xmlChar *)str free:(BOOL)freeOriginal {
if (!str) return nil;
NSString *string = [NSString stringWithCString:(char*)str encoding:NSUTF8StringEncoding];
if (freeOriginal)
xmlFree(str);
return string;
}
精彩评论