使用西班牙语(非UTF-8格式)解析xml文件

时间:2012-12-12 16:54:16

标签: iphone ios ipad xml-parsing

我需要用西班牙语解析xml文件(我无法控制如何生成)。解析部分工作得很好,但问题是当xml文件有特殊字符时,例如:

Espectáculos

什么时候解析我得到这个: áculos

我正在使用CocoaXMLParser。你们中的任何人都知道如何处理这个问题?

这是我的代码:

-(void)getRss
{
    NSString *urlString=@"http://mysite.com/content.xml";
    NSURL *url=[NSURL URLWithString:urlString];
    NSURLRequest *rssRequest=[NSURLRequest requestWithURL:url];
    self.contentConnection=[[NSURLConnection alloc]initWithRequest:rssRequest delegate:self startImmediately:YES];


}




- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {


    self.dataResponse = [NSMutableData data];

    NSLog(@"didReceiveResponse");

}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [_dataResponse appendData:data];

     NSLog(@"didReceiveData");




}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

    NSLog(@"didFailWithError");

}



- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

     NSLog(@"connectionDidFinishLoading ");

     [self parseContent];
}


-(void)parseContent
{
    NSString *response = [[NSString alloc] initWithData:_dataResponse encoding:NSUTF8StringEncoding];
    NSLog(@"data received %@", response);
    NSLog(@"parse content ");

    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:_dataResponse];
    parser.delegate = self;
    [parser parse];


}


- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    self.currentNodeContent = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if ([elementname isEqualToString:@"categoriaNoticias"])
    {
            self.validXML=YES;
        NSLog(@"es xml valido");

    }
    else
    {
         self.validXML=YES;
    }
}

- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if (_validXML) {
        if ([elementname isEqualToString:@"titulo"])
        {
            NSString *string=_currentNodeContent;
            NSLog(@"titulo %@", string);
        }
        if ([elementname isEqualToString:@"link"])
        {
        NSLog(@"titulo %@", _currentNodeContent);
    }

}

}

我真的很感激任何指针

1 个答案:

答案 0 :(得分:0)

假设您的XML文件是用Latin-1(ISO-8859-1)编码的,您可以动态修复XML文件:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    const char* xmlDecl = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\r\n";
    self.dataResponse = [NSMutableData data];
    [self.dataResponse appendBytes: xmlDecl length: strlen(xmlDecl)];
}

请检查有效编码是什么,并根据需要进行相应调整。