除了存储在NSArray中的dog之外,所有元素都存储在NSStrings中。我希望将所有狗条目添加到NSArray中。现在只有一个狗值被添加到数组中。如何将所有狗值添加到NSArray?
<root>
<element>
<person>Jim<person/>
<age>21<age/>
<dog>Labrador<dog/>
<dog>Beagle<dog/>
<dog>Yorkshire Terrier<dog/>
<element/>
<element>
<person>Jill<person/>
<age>50<age/>
<dog>Boxer<dog/>
<dog>Pug<dog/>
<dog>Labrador<dog/>
<dog>Beagle<dog/>
<dog>Yorkshire Terrier<dog/>
<element/>
</root>
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {
if([elementName isEqualToString:@"root"]) {
//Initialize the array.
appDelegate.entries = [[NSMutableArray alloc] init];
}
else if([elementName isEqualToString:@"element"]) {
//Initialize the entry.
anEntry = [[Entry alloc] init];
//Extract the attribute here.
anEntry.entryID = [[attributeDict objectForKey:@"id"] integerValue];
NSLog(@"Reading id value :%i", anEntry.entryID);
}
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:@"root"])
return;
if([elementName isEqualToString:@"element"]) {
[appDelegate.entries addObject:anEntry];
anEntry = nil;
}
else
[anEntry setValue:currentElementValue forKey:elementName];
currentElementValue = nil;
}
答案 0 :(得分:0)
原因是钥匙狗有多个值 所以如果你说:
[anEntry setValue:currentElementValue forKey:elementName];
然后那个键(elementName)可能已经包含了一个值。你正在使用解析器,你已经理解它是如何工作的,唯一的是你必须考虑所有的标签,而不仅仅是元素和root。 if-then.else你还必须考虑标签是狗的情况:
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if([elementName isEqualToString:@"root"])
return;
if([elementName isEqualToString:@"element"]) {
[appDelegate.entries addObject:anEntry];
anEntry = nil;
}
else if([elementName isEqualToString: @"dog"])
{
[anEntry.dogs addObject: currentElementValue];
}
else
[anEntry setValue:currentElementValue forKey:elementName];
currentElementValue = nil;
}
这种情况下你的入门类应该有一个名为dogs的属性,它是一个NSMutableArray,可读。