0

我无法解析 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

4

1 回答 1

0

标签“内容:编码”中某处的问题。请使用以下代码:

- (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);   
}
于 2012-11-03T10:30:13.633 回答