本文介绍了NSXMLParser如何将NSMutableDictionary传递给NSMutableArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将正在创建的nsdictionary传递到nsmutablearray中,但是我不确定何时或如何在nsxmlparser委托中进行操作.
I would like to pass the nsdictionary I am creating into an nsmutablearray but I'm not sure when or how to do it in the nsxmlparser delegates.
这是我到目前为止所做的
this is what I have done so far
#pragma mark - Parsing lifecycle
- (void)startTheParsingProcess:(NSData *)parserData
{
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:parserData]; //parserData passed to NSXMLParser delegate which starts the parsing process
[parser setDelegate:self];
[parser parse]; // starts the event-driven parsing operation.
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:@"item"]) {
valueDictionary = [[NSMutableDictionary alloc] init];
}
}
-(void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock
{
NSMutableString *dicString = [[NSMutableString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding];
currentElement = dicString;
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:@"title"]) {
titleString = currentElement;
[self.valueDictionary setObject:titleString forKey:@"title"];
NSLog(@"%@", [valueDictionary objectForKey:@"title"]);
NSLog(@" ");
currentElement = nil;
}
if ([elementName isEqualToString:@"description"])
{
descriptionString = currentElement;
[self.valueDictionary setObject:descriptionString forKey:@"description"];
NSLog(@"%@", [valueDictionary objectForKey:@"description"]);
NSLog(@" ");
currentElement = nil;
}
推荐答案
在 -parser:didEndElement:namespaceURI:qualifiedName:
中,侦听 item
元素的结尾,然后将 valueDictionary
添加到类中的可变数组实例中.
In -parser:didEndElement:namespaceURI:qualifiedName:
, listen for the end of the item
element, then add valueDictionary
to a mutable array instance on your class.
if ([elementName isEqualToString:@"item"])
{
[self.mutableArrayOfDictionaries addObject:self.valueDictionary];
}
if ([elementName isEqualToString:@"title"]) {
titleString = currentElement;
[self.valueDictionary setObject:titleString forKey:@"title"];
NSLog(@"%@", [valueDictionary objectForKey:@"title"]);
NSLog(@" ");
currentElement = nil;
}
if ([elementName isEqualToString:@"description"])
{
descriptionString = currentElement;
[self.valueDictionary setObject:descriptionString forKey:@"description"];
NSLog(@"%@", [valueDictionary objectForKey:@"description"]);
NSLog(@" ");
currentElement = nil;
}
这篇关于NSXMLParser如何将NSMutableDictionary传递给NSMutableArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!