0

我在这个问题上有点卡住了。情况如下:我正在解析一个带有位置的 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));

}

}

这是我的代码。它解析得很好,但是我的 NSMutableArray (modulectrle) 充满了奇怪的 NSDictionaries...

4

1 回答 1

-1

在 while 循环内分配 NSDictionary:

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));

否则,您将再次将相同的 NSDictionary 添加到数组中,然后将所有元素推送到同一个字典中,结果您会多次获得具有相同字典的数组。

于 2013-09-16T14:56:35.483 回答