How can we parse an XML with ISO-8859-15 encoding? - iphone

I was using UTF-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;
}

Related

Parsing XML String From WebServer

Alright, so here's where I'm at with my app.
I've got some code that connects to a remote server and grabs some XML data, and forms it into a string. Here is the code below:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSString *accept = [NSString stringWithFormat:#"application/xml"];
[request addValue:accept forHTTPHeaderField: #"Accept"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString* responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"%#",responseString);
Which returns
That's exactly the information I want. My question is how I can get the double value out of the gold brackets and into my application to use.
Thanks a lot!
There are a lot of tutorials of how to use NSXMLParser. For example, ray wenderlich or here and here.
There's quite a few XML parsing options available - ranging from libxml2, to NSXMLParser and a host of open-source projects.
One of my favorite XML parsers is RaptureXML, which can be installed via CocoaPods.
I like to create a category on RXMLElement to parse as follows:
- (PFCurrentConditions*)asCurrentCondition
{
NSString* summary = [[self child:#"weatherDesc"] text];
PFTemperature* temp = [PFTemperature temperatureWithFahrenheitString:[[self child:#"temp_F"] text]];
NSString* humidity = [[self child:#"humidity"] text];
NSString* wind =
[NSString stringWithFormat:#"Wind: %# km %#", [[self child:#"windspeedKmph"] text], [[self child:#"winddir16Point"] text]];
NSString* imageUri = [[self child:#"weatherIconUrl"] text];
return [PFCurrentConditions conditionsWithSummary:summary temperature:temp humidity:humidity wind:wind imageUrl:imageUri];
}
So, you can then use it as follows:
RXMLElement* rootElement = [RXMLElement elementFromXMLData:response.responseData];
__autoreleasing PFWeatherReport* weatherReport = [rootElement asWeatherReport];
Again, this is one of countless options, but my personal favorite.

Convert Unicode character to NSString

I have received string from webservice which contains Unicode character. I want to convert that To plain NSString. so How can i do that?
ex: "This isn\u0092t your bike"
So how can remove unicode and replace it with its equal special symbol characted.
The output would be : "This isn't your bike"
char cString[] = "This isn\u2019t your bike";
NSData *data = [NSData dataWithBytes:cString length:strlen(cString)];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"result string: %#", string);
This should work.
UPDATE FOR THE COMMENT:
The unicode character specified by you is not supported in all fonts.
http://www.fileformat.info/info/unicode/char/92/fontsupport.htm
But this one does.
http://www.fileformat.info/info/unicode/char/2019/fontsupport.htm
Thats why it throws an error.
NSString *final_url = [NSString stringWithFormat:url];
final_url = [final_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:final_url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:120.0];
NSURLResponse *response;
NSError *error = [[NSError alloc] init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *strResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
SBJSON *objJSON = [SBJSON new];
NSMutableDictionary *objDataDic = [objJSON objectWithString:strResponse error:nil];
There is a library which does conversion
https://github.com/alexaubry/HTMLString. It will convert all kind of Unicode character.
let escapedSnack = "Fish & Chips"
let snack = escapedSnack.removingHTMLEntities // "Fish & Chips"

How to use stringWithContentsOfURL:encoding:error:?

I am trying to use initWithContentsOfURL:encoding:error: like this :
NSURL *url = [[NSURL alloc] initWithString:#"http://my_url.com/my_file.xml"];
NSError *error = nil;
NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:&error];
I get a empty my_string variable.
I tried the initWithContentsOfURL: method (which is deprecated in iOS 2.0) and I get the content of my page. But I still need to specify a encoding language.
What's wrong ?
Thanks :)
the encoding of your file is probably not UTF8.
If you don't know the encoding of your file, you could try this method:
- (id)initWithContentsOfURL:(NSURL *)url usedEncoding:(NSStringEncoding *)enc error:(NSError **)error
you have to pass a pointer to a NSStringEncoding, like you did with error.:
NSURL *url = [[NSURL alloc] initWithString:#"http://my_url.com/my_file.xml"];
NSError *error = nil;
NSStringEncoding encoding;
//NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
// encoding:NSUTF8StringEncoding
// error:&error];
NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
usedEncoding:&encoding
error:&error];
after this your encoding is present in the encoding variable. If you are not interested in the used encoding, I guess you could pass NULL as pointer as well.
Why not use a request and connection to get the info back in an NSData object? Something like this:
NSURL *url = [[NSURL alloc] initWithString:#"http://my_url.com/my_file.xml"];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"GET"];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[conn start];
if(conn){
// Data Received
responseData = [[NSMutableData alloc] init];
}
and then in your connection:didRecieveData delegate method, put something like this
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.responseData appendData:data];
}
and then once the connection is finished loading convert the data to a string:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *string = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
}
Not the most straightforward method, but that should get you your XML string. Also if you need to parse the XML once you get it back, you can directly pass the responseData to an NSXMLParser without any conversion. :)
You can modify your webpage by adding header('Content-Type: text/html; charset=UTF-8'); to the top of the code and saving the document as a UTF-8 formated file. It helped me as I had the same problem.

NSURLErrorBadURL error

My iphone app called Google Local Search(non javascript version) to behave some search business.
Below is my code to form a url:
NSString *url = [NSString stringWithFormat:#"http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=%#", keyword];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"GET"];
//get response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[[NSError alloc] init] autorelease];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
When the keyword refers to english characters, it works fine, but when refers to chinese characters(encoded in UTF8, such as '天安门' whose UTF8 code is 'e5a4a9 e5ae89 e997a8'), it will report NSURLErrorBadURL error(-1000, Returned when a URL is sufficiently malformed that a URL request cannot be initiated). Why?
Then I carry out further investigation, I use Safari and type in the url below:
http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=天安门
It also works, and the output I got from Macsniffer is:
/ajax/services/search/local?v=1.0&q=%E5%A4%A9%E5%AE%89%E9%97%A8
So I write a testing url directly in my app
NSString *url = [NSString stringWithFormat:#"http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=%E5%A4%A9%E5%AE%89%E9%97%A8"];
And what I got from the Macsniffer is some other thing:
/ajax/services/search/local?v=1.0&q=1.687891E-28750X1.417C0001416CP-102640X1.4CC2D04648FBP-9999-1.989891E+0050X1.20DC00184CC67P-953E8E99A8
It seems my keyword "%E5%A4%A9%E5%AE%89%E9%97%A8" was translated into something else. So how can I form a valid url? I do need help!
Have you tried encoding the search string:
NSString* escapedKeyword = [keyword stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

iPhone NSString convert to readable text

I have a piece of NSString that will read "Test & Test" or with "
Is there any way without searching and replacing to make that display as "&" or """ ??
Can you try this ?
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.mypage.com/content.html"]]];
[request setHTTPMethod:#"GET"];
NSHTTPURLResponse* authResponse;
NSError* authError;
NSData * authData = [NSURLConnection sendSynchronousRequest:request returningResponse:&authResponse error:&authError];
NSString *authResponseBody = [[NSString alloc] initWithData:authData encoding:NSUTF8StringEncoding];
NSLog(#" Nice Result: %#", authResponseBody);
Adrian
CFXMLCreateStringByUnescapingEntities should do it. Thanks to the magic of toll free bridging you can just use your NSString.
The html string you read is bad formated.
Try to read as UTF-8 or any other formatting in order to get the correct text from the html you're reading.
Can you actually post the code where you read the NSString from the HTML content ?