[英]Loading NSDictionary parsing xml file
I've been stuck a little on this problem. 我在这个问题上有些卡住了。 Here is the situation : I'm parsing an xml file with positions, I parse it well, thing is I want to put the different elements into an NSDictionary (one NSDictionary for each position) and those NSDictionary into an NSMutableArray.
这是一种情况:我正在解析一个带有位置的xml文件,我很好地解析了它,我想将不同的元素放入NSDictionary(每个位置一个NSDictionary),并将那些NSDictionary放入NSMutableArray。
- (void) traverseElement:(TBXMLElement *)element {
NSMutableDictionary *position = [[NSMutableDictionary alloc]init];
NSArray *keys = [NSArray arrayWithObjects:@"cab",@"idagencedepart", @"idagencefinale",@"iddestinataire",@"idexpediteur",@"idtransporteurreexpedition",@"departement",@"message1", nil];
[position dictionaryWithValuesForKeys:keys];
do {
TBXMLAttribute * attribute = element->firstAttribute;
// if attribute is valid
while (attribute) {
if ([[TBXML elementName:element] isEqualToString:@"referencecolis"]) {
[position setObject:[TBXML textForElement:element] forKey:@"cab"];
NSLog(@"cab : %@",[TBXML textForElement:element]);
};
if ([[TBXML elementName:element] isEqualToString:@"idagencedepart"]) {
[position setObject:[TBXML textForElement:element] forKey:@"idagencedepart"];
NSLog(@"idagencedepart : %@",[TBXML textForElement:element]);
};
[modulectrlcle addObject:position];
attribute = attribute->next;
}
if (element->firstChild)
[self traverseElement:element->firstChild];
} while ((element = element->nextSibling));
} }
} }
Here is my code. 这是我的代码。 It parses well, but my NSMutableArray (modulectrle) is filled with weird NSDictionaries...
它解析得很好,但是我的NSMutableArray(modulectrle)充满了奇怪的NSDictionaries ...
Allocate NSDictonary inside while loop: 在while循环内分配NSDictonary:
do {
TBXMLAttribute * attribute = element->firstAttribute;
while (attribute) {
NSMutableDictionary *position = [[NSMutableDictionary alloc]init];
BOOL foundElement = NO;
if ([[TBXML elementName:element] isEqualToString:@"referencecolis"]) {
[position setObject:[TBXML textForElement:element] forKey:@"cab"];
NSLog(@"cab : %@",[TBXML textForElement:element]);
foundElement = YES;
};
if ([[TBXML elementName:element] isEqualToString:@"idagencedepart"]) {
[position setObject:[TBXML textForElement:element] forKey:@"idagencedepart"];
NSLog(@"idagencedepart : %@",[TBXML textForElement:element]);
foundElement = YES;
};
if(foundElement) //avoid adding empty NSDictonaries
{
[modulectrlcle addObject:position];
}
attribute = attribute->next;
}
if (element->firstChild)
[self traverseElement:element->firstChild];
} while ((element = element->nextSibling));
Otherwise you add same NSDictonary all over again to an array and you push all elements into same dictionary and as a result you get array with a same dictionary several times. 否则,您将相同的NSDictonary再次添加到数组中,然后将所有元素推入相同的字典中,结果将多次获得具有相同字典的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.