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

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

输出是:

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

这里是xml https://www.dropbox.com/s/x4zpxgi42h0rllz/Demo.xml 的链接

最佳答案

未经测试,但

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

应该可以

关于iphone - 如何将所有字典存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18513092/

相关文章:

ios - AVPlayer 是否支持在单独的文本文件中提供的隐藏式字幕?

iphone - TBXML "class method tbXMLWithURL not found"

objective-c - TBXML 中的异步和 initWithURL

iphone - iphone5 IOS录音时如何使用振动?

iphone - 创建ipa文件,配置ad hoc配置文件出现很多错误

ios - 当前 UIActivityViewController- LaunchServices :invalidationHandler called

ios - 将 .p12 证书存储在钥匙串(keychain)中以备后用

ios - 如何在使用 xcode 开发 ios 应用程序时读取 csv 文件

iphone - 如何在 iphone 中将数据传递给 Tbxml

ios - 是否可以弹出到 n - 2 或 n - 3 View ?