简体   繁体   English

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

[英]how to store all dictionary in an array

i have an xml file which contains country and codes. 我有一个包含国家和代码的xml文件。 i have put the xml in Demo.xml .My problem is that only first dictionary has been saved. 我把xml放在Demo.xml中。我的问题是只保存了第一个字典。 or anyone can tell me other way of parsing it like using nsxml or gdata 或者任何人都可以告诉我解析它的其他方式,如使用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);

And the outPut is: outPut是:

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

Here is the link of xml https://www.dropbox.com/s/x4zpxgi42h0rllz/Demo.xml 这是xml的链接https://www.dropbox.com/s/x4zpxgi42h0rllz/Demo.xml

Not tested but 没有测试但是

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

should work 应该管用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM