我已经解析了xml文件 控制台正确显示已解析的元素,但数组显示为null。
- (ParserClass *) initXMLParser
{
//[super init];
appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
return self;
}
- (void)parser: (NSXMLParser *)parser didStartElement:(NSString *) elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {
if([elementName isEqualToString:@"note"]) {
//Initialize the array.
appDelegate.testArray = [[NSMutableArray alloc] init];
}
else if([elementName isEqualToString:@"to"]) {
aTest = [[Test alloc] init];
}
NSLog(@"Processing Element: %@", elementName);
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if(!currentElementValue)
currentElementValue = [[NSMutableString alloc] initWithString:string];
else
[currentElementValue appendString:string];
NSLog(@"Processing Value: %@", currentElementValue);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if([elementName isEqualToString:@"Books"])
return;
if([elementName isEqualToString:@"note"]) {
[appDelegate.testArray addObject:aTest];
//[aBook release];
aTest = nil;
}
else
[aTest setValue:currentElementValue forKey:elementName];
//[currentElementValue release];
currentElementValue = nil;
}
@end
答案 0 :(得分:0)
尝试将初始化更改为:
- (ParserClass *) initXMLParser {
self=[super init];
if(self !=nil){
appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
// init array of user objects here
appDelegate.testArray = [[NSMutableArray alloc] init];
}
return self;
}
而且,如果你的xml是:
<books>
<note>
<something>cccc</something>
</note>
<note>
<something>cccc</something>
</note>
</books>
所以你需要改变:
-(void)parser: (NSXMLParser *)parser didStartElement:(NSString *) elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {
if([elementName isEqualToString:@"note"]) {
aTest = [[Test alloc] init];
//if you have attributes, you can extract them here:
// user.att = [[attributeDict objectForKey:@"<att name>"] ...];
}
NSLog(@"Processing Element: %@", elementName);
}
要获得你的阵列,你必须做这样的事情:
//Data store your xml
NSXMLParser *nsXmlParser = [[NSXMLParser alloc] initWithData:Data];
ParserClass *parser = [[ParserClass alloc] initXMLParser];
//delegate your parser
[nsXmlParser setDelegate:parser];
//it's doing parsing
BOOL success = [nsXmlParser parse];
if (success)
{
NSMutableArray *someArray = [parser appDelegate.testArray ];
NSLog(@"%@",someArray );
} else
{
NSLog(@"Error parsing document!");
}
尝试一下,它适合我...