Вы уже на правильном пути. NSXMLParser
начнет вызывать эти методы, когда вы вызовете метод parse
для него. Поскольку в вашем вопросе есть пример xml, вот пример (ruff) того, как реализовать пользовательский класс NSXMLParserDelegate
. Обратите внимание, что я скопировал вышеупомянутый xml в файл с именем "MatrixList.xml" в папке моего проекта.
MatrixList.h
#import <Foundation/Foundation.h>
@interface MatrixList : NSObject <NSXMLParserDelegate>
@property (readonly) NSMutableArray *rows; // property to access results
-(id)initWithContentsOfURL:(NSURL *)url;
@end
MatrixList.m
:
#import "MatrixList.h"
@implementation MatrixList{
NSXMLParser *parser;
NSMutableString *charactersFound;
}
@synthesize rows = _rows;
-(void)parserDidStartDocument:(NSXMLParser *)parser{
// These objects are created here so that if a document is not found they will not be created
_rows = [[NSMutableArray alloc] init];
charactersFound = [[NSMutableString alloc] init];
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
// clear the characters for new element
[charactersFound setString:@""];
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
// add string found to the mutable string
[charactersFound appendString:string];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:@"row"]){
// If we are done with a row add the rows contents, a string, to the rows array
[_rows addObject:[charactersFound copy]];
}
[charactersFound setString:@""];
}
-(void)parserDidEndDocument:(NSXMLParser *)parser{
// This method is handy sometimes
}
-(void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{
NSLog(@"error:%@",parseError.localizedDescription);
}
-(id)initWithContentsOfURL:(NSURL *)url{
if ((self = [super init])){
parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
parser.delegate = self;
[parser parse]; // This is for an example, You might not want to call parse here, depending on context
}
return self;
}
@end
Этот класс используется примерно так:
// My copy is in the bundle, You could use a url for the docs directory instead
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"MatrixList" withExtension:@"xml"];
MatrixList *matrix = [[MatrixList alloc] initWithContentsOfURL:fileURL];
NSLog(@"rows:%@",matrix.rows);
С приведенным выше кодом консоль выдаст:
rows:(
"eraser*met",
"debone*anat",
"ani*jalisco",
"madwoman*on",
"**joy*itsme",
"isao***amad",
"mends*mio**",
"be*parental",
"insipid*hai",
"bail*modern",
"esse*scored"
)
Этот код вообще не уточняется, но я думаю, что это хороший общий пример того, как анализировать некоторые базовые xml.