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];
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];
}
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)];
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]);
}
Related
I am Getting a weird problem. I am making an App which should run on Both iOS 4 & 5.When i parse my XML in iOS 5 It is doing great and i am getting my output, but when i am Trying to do the same in iOS 4 ,i am getting this error "NSXMLParserErrorDomain error 31". in the
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError;
my XML is like this.. i need to parse the title tag within Item tag...
<item> <title> <![CDATA[ Cynical approach to tar my reputation: Army Chief on leaked letter ]]> </title> <link> <![CDATA[ ]]> </link> <guid isPermaLink="false"> <![CDATA[ ]]> </guid> </item> <item> <title> <![CDATA[ Major fire in scrap godown in suburban Mumbai ]]> </title> <link> <![CDATA[ ]]> </link> <guid isPermaLink="false"> <![CDATA[ ]]> </guid> </item>
My parsing code id this :-
-(void)parseBN{
NSString *URL=#"My XML's URL";
// convert the path to a proper NSURL
NSURL *xmlURL = [NSURL URLWithString:URL];
CTNetworking *request= [CTNetworking requestWithUrl:xmlURL];
[request setDelegate:self];
[request setDidFinishSelector:#selector(startParse:)];
[request startRequest];
}
-(void)startParse:(CTNetworking*)response{
if (response.responseStatusCode == 200 && rssParser == nil) {
[stories removeAllObjects];
NSString *myStr = [[NSString alloc] initWithData:[response responseData] encoding:NSWindowsCP1251StringEncoding];
myStr = [myStr stringByReplacingOccurrencesOfString:#"encoding=\"windows-1251\"" withString:#""];
NSData* aData = [myStr dataUsingEncoding:NSASCIIStringEncoding];
// NSXMLParser *parser = [[NSXMLParser alloc] initWithData:aData];
rssParser = [[NSXMLParser alloc] initWithData:aData];
// rssParser = [[NSXMLParser alloc] initWithData:[response responseData]];
// Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
[rssParser setDelegate:self];
// Depending on the XML document you're parsing
[rssParser setShouldProcessNamespaces:NO];
[rssParser setShouldReportNamespacePrefixes:NO];
[rssParser setShouldResolveExternalEntities:NO];
[rssParser parse];
}
}
- (void)parserDidStartDocument:(NSXMLParser *)parser{
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
NSString * errorString = [NSString stringWithFormat:#"Unable to download story feed from web site (Error code %i )", [parseError code]];
NSLog(#"error parsing XML: %#", errorString);
UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:#"Error loading content" message:errorString delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
It is not coming here.. so didn't paste the Inside code
}
I searched in google for this error and everybody saying this error comes because of Unknown Encoding.. so i tried with "NSWindowsCP1251StringEncoding" also instead of default Encoding.
Any Help will be Appreciated.
Finally i got it working...
NSString *myStr = [[[NSString alloc] initWithData:[response responseData] encoding:NSWindowsCP1251StringEncoding] autorelease];
myStr = [myStr stringByReplacingOccurrencesOfString:#"encoding=\"windows-1251\"" withString:#""];
myStr = [myStr stringByReplacingOccurrencesOfString:#"US-ASCII" withString:#"UTF-8"];
NSData* aData = [myStr dataUsingEncoding:NSASCIIStringEncoding];
rssParser = [[NSXMLParser alloc] initWithData:aData];
[rssParser setDelegate:self];
[rssParser setShouldProcessNamespaces:NO];
[rssParser setShouldReportNamespacePrefixes:NO];
[rssParser setShouldResolveExternalEntities:NO];
[rssParser parse];
Changed the Encoding type through NSString :)
I have a class which parse an XML feed. In that class I have to following method:
-(id)loadXMLByURL:(NSString *)urlString name:(NSString*)name{
NSString *urls = [[NSString alloc]initWithFormat:#"%#%#" , urlString, name];
NSLog(#"STRING URL: %#" , urls);
NSURL *url = [NSURL URLWithString:urls];
NSLog(#"%#" , url);
parser = [[NSXMLParser alloc]initWithContentsOfURL:url];
parser.delegate = self;
BOOL success = [parser parse];
if (success) {
NSLog(#"No error");
}else{
NSLog(#"Error: %#" , parser.parserError);
}
return self;
}
The first NSLog is the correct url, however the NSURL comes out as (null)
Here's where I call the method:
//f is an object where I store the value of name from another feed, which I have to use as a parameter in the url for this feed
NSString *name = f.name;
myParser = [[MyParser alloc]loadXMLByURL:#"http://myurl.com/names.asp?name=" name:name];
If I NSLog name here, it shows the right value.
Anyone have any idea why the NSURL comes out as (null)?
You'll want to escape name.
Add a category on NSString and then call [name urlEncodedString]. e.g.:
#implementation NSString (URLEncoding)
- (NSString *)urlEncodedString
{
return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)self,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
kCFStringEncodingUTF8);
}
#end
Use the following..
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat::#"%#%#" , urlString, name]]];
parser = [[NSXMLParser alloc] initWithData: data];
parser.delegate = self;
BOOL success = [parser parse];
if (success) {
NSLog(#"No error");
}else{
NSLog(#"Error: %#" , parser.parserError);
}
return self;
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];
}
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];
Very similar to sepehr-mahmoudian's answer, but instead of replace any & you should really just replace & characters that are unescaped, to do this you can use a regexp:
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];
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];
Here's what worked for me:
NSString *response = [[NSString alloc]initWithData:dataResponse encoding:NSUTF8StringEncoding];
NSString *newResponse = [response stringByReplacingOccurrencesOfString:#"&:" 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'.
To all
I am trying to parser the xml in my project But I have the code for xml parsing for locally I want the server base xml parsing how can i pass that
This is my xml parsing link i want to use:
http://www.google.com/ig/api?weather=,,,50500000,30500000
This my xml parsing for calling local file how can I call my webserver xml link for parsing.I need different-differnet type of calling xml link for parsing:
- (void)viewDidLoad
{
[super viewDidLoad];
_forecastInfo=nil;
currentcond=nil;
forecastcond=nil;
// Pass the NSData to the parser whether its from local file or its coming from web.... NSString *fileName=[[NSBundle mainBundle] pathForResource:#"weather" ofType:#"xml"];
NSData *data=[NSData dataWithContentsOfFile:fileName];
ForecastInfoParser *parser=[[ForecastInfoParser alloc]init];
parser.delegate=self;
[parser parseData:data];
}
NSURL *url = [[NSURL alloc] initWithString:#"hhttp://www.google.com/ig/api?weather=,,,50500000,30500000"];
NSData *data = [NSData dataWithContentsOfURL:url];
// 2 -- parsing
parser = [[MyParser alloc] init];
[parser parseXML:data];
NSString *URL=#"http://www.google.com";
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:URL]];
NSURLResponse *resp = nil;
NSError *err = nil;
NSData *response = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: &resp error: &err];
NSString * theString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
[resp release];
[err release];
NSLog(#"response: %#", theString);
I need to parse a XML feed with french accent like 'é' .
When I parse the XML I lost the accents...
What's wrong in my code...
NSString *url = [NSString stringWithFormat:#"%#",#"my_xml_url"];
NSURL *myURL = [NSURL URLWithString:url];
NSString *myData = [[NSString alloc] initWithContentsOfURL:myURL];
XMLParser *parser = [[XMLParser alloc] init];
[parser parseXMLFile:myData];
And when I start parsing.....
- (void)parseXMLFile:(NSString *)data {
BOOL success;
//array for the ranking
rows = [[NSMutableArray alloc] init];
index = 0;
self.currentString = [NSMutableString string];
storingCharacters = NO;
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:[data data UsingEncoding:NSUTF8StringEncoding]];
[parser setDelegate:self];
[parser setShouldResolveExternalEntities:YES];
success = [parser parse];
self.currentString = nil;
//release memory
[parser release];
}
I can't see where is the problem...
Thanks
It appears to be an encoding issue with stringWithContentsOfURL
Try:
NSError *lookupError = nil;
NSString *myData = [NSString stringWithContentsOfURL:myUrl
encoding:NSUTF8StringEncoding error:&lookupError];
You're first reading the XML data and converting it to an NSString, then later converting that string back into data. As krtrego said, the to-string conversion is probably picking the wrong encoding. Instead, you should feed the raw data from the URL directly into NSXMLParser, which is smarter about being able to interpret the correct encoding (i.e. using the metadata at the top of the XML file.)
So instead use
NSData* myData = [[NSData dataWithContentsOfURL: url options: 0 error: &error];
then pass that data when initializing the NSXMLParser.