NSXMLParser和带有奇怪编码的xml

时间:2012-11-03 08:40:50

标签: ios xml encoding nsxmlparser

我无法解析XML文件

最初,我将我的解析器声明为:

NSURL *url = [[NSBundle mainBundle] URLForResource:@"download.rss" withExtension:@"webintents"];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];

解析时,我遇到错误

  

NSXMLParserErrorDomain错误9

我检查它是NSXMLParserInvalidCharacterError。

在解析器运行多个标记并在标记处遇到错误之后

然后我将声明更改为迭代编码:

NSError *errorOfStr = nil;
NSStringEncoding encoding;
NSString *xmlFeedStr = [NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"download.rss" withExtension:@"webintents"] usedEncoding:&encoding error:&errorOfStr];

NSXMLParser *parser = [[NSXMLParser alloc] initWithData:[xmlFeedStr dataUsingEncoding:encoding allowLossyConversion:YES]];

但是在初始化变量“xmlFeedStr”时遇到错误。检查“errorOfStr”,我看到了错误:

  

可可错误264

我检查一下,它是NSFileReadUnknownStringEncodingError

之后,我尝试对文件强制进行NSUTF8StringEncoding或NSUnicodeStringEncoding的编码,如下所示:

NSStringEncoding encoding = NSUnicodeStringEncoding;
NSString *xmlFeedStr = [NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"download.rss" withExtension:@"webintents"] encoding:encoding error:&error];

但没有成功。我遇到了一些Cocoa错误,因为无法加载文件或加载没有内容的文件。

请帮帮我?

我把文件放在:

http://www.mediafire.com/download.php?yxfp3ch8n3ai4iq

1 个答案:

答案 0 :(得分:0)

标签“content:encoded”中的问题。请使用以下代码:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    NSLog(@"Application Did Finish Launching");

    NSString *dataString = [[[NSString alloc] initWithContentsOfFile:@"/Users/alex/Downloads/download.rss.webintents" encoding:NSASCIIStringEncoding error:nil] autorelease];

    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
    [parser setDelegate:self];
    [parser parse];
    [parser release];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
    NSLog(@"Did Start Element: %@", elementName);
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    NSLog(@"Found Characters: %@", string);
}

- (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock
{
    NSString *someString = [[NSString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding];
    NSLog(@"Found CDATA: %@", someString);
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    NSLog(@"Did End Element: %@", elementName);
}

- (void)parserDidEndDocument:(NSXMLParser *)parser
{
    NSLog(@"Parser Did End Document");
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
    NSLog(@"Parse Error Occurred: %@", parseError.description);   
}