我按照网络上的简单教程使用 NSXMLParser 解析 xml。委托对象初始化,但从不触发 NSXMLParser 委托方法。我做错了什么?我在 windows 上使用 GNUSetup。
这是我调用解析器的地方:
-(BOOL) loadXmlPath :(NSString*)filePathXml:(NSString*) filePathWrite
{
if([fileMgr fileExistsAtPath:filePathXml] == YES)
{
NSLog(@"%@",filePathXml);
NSURL *xmlURL = [NSURL fileURLWithPath:filePathXml];
NSXMLParser *nsXmlParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
if(nsXmlParser)
{
NSLog(@"done setup parser");
}
else
{
NSLog(@"fail setup parser");
}
// create and init our delegate
XMLParser *parser = [[XMLParser alloc] initXMLParser];
[nsXmlParser setShouldProcessNamespaces:NO]; // We don't care about namespaces
[nsXmlParser setShouldReportNamespacePrefixes:NO]; //
[nsXmlParser setShouldResolveExternalEntities:NO]; // We just want data, no other stuff
// set delegate
[nsXmlParser setDelegate:parser];
// parsing...
BOOL success = [nsXmlParser parse];
// test the result
if (success) {
NSLog(@"parsing document!");
// get array of users here
} else {
if ([nsXmlParser parserError]) {
NSError *err = [nsXmlParser parserError];
NSString *serror = [err localizedDescription];
NSLog(@"Error parsing document!%@\n",serror);
}
NSLog(@"Error parsing document!");
}
}
return NO;
}
XmlParser.h
#import <Foundation/Foundation.h>
@interface XMLParser : NSObject
{
NSXMLParser *parser;
}
-(XMLParser *) initXMLParser;
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict;
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string;
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName;
@end
XmlParser.m
#import "XMLParser.h"
@implementation XMLParser
- (XMLParser *) initXMLParser {
self = [super init];
NSLog(@"Init xml parser");
return self;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
NSLog(@"Enter parser 1");
if ( [elementName isEqualToString:@"name"]) {
NSLog(@"%@",elementName);
return;
}
if ( [elementName isEqualToString:@"person"] ) {
return;
}
if ( [elementName isEqualToString:@"lastName"] ) {
return;
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
NSLog(@"Enter parser 2");
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
NSLog(@"Enter parser 3");
if (( [elementName isEqualToString:@"addresses"]) ||
( [elementName isEqualToString:@"address"] )) return;
if ( [elementName isEqualToString:@"person"] ) {
return;
}
}
@end
它永远不会到达解析器方法。但它确实到达了 initXMLParser 。我在这里做错了什么?我也进入了:[errlocalizedDescription] 这个消息:
NSXMLParserErrorDomain 3
这是什么意思 ?