我正在解析一个 xml 文件,它可以工作并向我显示在控制台中解析的数据(例如:Speller 的处理值 ...),但它们不会添加到 msmutablearray 用户中。这是一些代码。问题出在哪里 ?请帮忙 :
- (MyData *) initXMLParser {
[super init];
// init array of user objects
users = [[NSMutableArray alloc] init];
return self;
}
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:@"user"]) {
NSLog(@"user element found – create a new instance of User class...");
user = [[User alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if (!currentElementValue) {
// init the ad hoc string with the value
currentElementValue = [[NSMutableString alloc] initWithString:string];
} else {
// append value to the ad hoc string
[currentElementValue appendString:string];
}
NSLog(@"Processing value for : %@", string);
}
- (void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:@"users"]) {
// We reached the end of the XML document
return;
}
if ([elementName isEqualToString:@"user"]) {
if ([elementName isEqualToString:@"userName"]) {
[[self user] setUserName:currentElementValue];
}
if ([elementName isEqualToString:@"firstName"]) {
[[self user] setFirstName:currentElementValue];
}
if ([elementName isEqualToString:@"lastName"]) {
[[self user] setLastName:currentElementValue];
}
[users addObject:user];
/*comboarray = [[users arrayForKey:@"ComboBoxValues"]
sortedArrayUsingSelector:@selector(compare:)];*/
// release user object
[user release];
user = nil;
} else {
[user setValue:currentElementValue forKey:elementName];
}
[currentElementValue release];
currentElementValue = nil;
}
-(BOOL)parseDocumentWithData:(NSData *)data {
//NSString * filePath = [[NSBundle mainBundle] pathForResource:@"Users" ofType:@"xml"];
//data = [NSData dataWithContentsOfFile:filePath];
if (data == nil)
return NO;
// this is the parsing machine
NSXMLParser *xmlparser = [[NSXMLParser alloc] initWithData:data];
// this class will handle the events
[xmlparser setDelegate:self];
[xmlparser setShouldResolveExternalEntities:NO];
// now parse the document
BOOL ok = [xmlparser parse];
if (ok == NO)
NSLog(@"error");
else
NSLog(@"OK");
[xmlparser release];
return ok;
}
- (void) dealloc {
[currentElementValue release];
[super dealloc];
}