1

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

看点

什么时候解析我得到这个:á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);
    }

}

}

我真的很感激任何指示

4

1 回答 1

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)];
}

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

于 2012-12-12T18:52:35.487 回答