如何在数组中存储所有字典

时间:2013-08-29 14:01:42

标签: iphone ios tbxml

我有一个包含国家/地区和代码的xml文件。我把xml放在Demo.xml中。我的问题是只保存了第一个字典。或者任何人都可以告诉我解析它的其他方式,如使用nsxml或gdata

NSString *filePath=[[NSBundle mainBundle] pathForResource:@"Demo" ofType:@"xml"];
NSData *data=[NSData dataWithContentsOfFile:filePath];
addArray=[[NSMutableArray alloc]init];
dictData=[[NSMutableDictionary alloc]init];


TBXML *tbxml = [TBXML tbxmlWithXMLData: data];
TBXMLElement *rootXMLElement=tbxml.rootXMLElement;

TBXMLElement *rootElemnt=[TBXML childElementNamed:@"root" parentElement:rootXMLElement];
while (rootElemnt!=nil) {

    TBXMLElement *item = [TBXML childElementNamed:@"item" parentElement:rootElemnt];

    if (item!=nil) {
        TBXMLElement *country = [TBXML childElementNamed:@"country" parentElement:item];
        TBXMLElement *code = [TBXML childElementNamed:@"code" parentElement:item];

        dictData=[NSMutableDictionary dictionaryWithObjectsAndKeys:[TBXML textForElement:country],@"country",[TBXML textForElement:code],@"code",nil];
        rootElemnt = [TBXML nextSiblingNamed:@"item" searchFromElement:rootElemnt];

        [addArray addObject:dictData];
    }
}
NSLog(@"====%@",addArray);

outPut是:

====(
        {
            code = 355;
            country = Albania;
        }
    )

以下是xml https://www.dropbox.com/s/x4zpxgi42h0rllz/Demo.xml

的链接

1 个答案:

答案 0 :(得分:2)

未经测试但

NSString *filePath=[[NSBundle mainBundle] pathForResource:@"Demo" ofType:@"xml"];
NSData *data=[NSData dataWithContentsOfFile:filePath];
addArray=[[NSMutableArray alloc]init];
dictData=[[NSMutableDictionary alloc]init];


TBXML *tbxml = [TBXML tbxmlWithXMLData: data];
TBXMLElement *rootXMLElement=tbxml.rootXMLElement;

TBXMLElement *rootElemnt=[TBXML childElementNamed:@"root" parentElement:rootXMLElement];
if (rootElemnt) {
    TBXMLElement *item = [TBXML childElementNamed:@"item" parentElement:rootElemnt];

    while (item) {

        TBXMLElement *country = [TBXML childElementNamed:@"country" parentElement:item];
        TBXMLElement *code = [TBXML childElementNamed:@"code" parentElement:item];

        dictData=[NSMutableDictionary dictionaryWithObjectsAndKeys:[TBXML textForElement:country],@"country",[TBXML textForElement:code],@"code",nil];

        [addArray addObject:dictData];
        item = [TBXML nextSiblingNamed:@"item" searchFromElement:item];
    }
}
NSLog(@"====%@",addArray);

应该有效