【问题标题】:how to store all dictionary in an array如何将所有字典存储在数组中
【发布时间】:2013-09-02 00:19:37
【问题描述】:

我有一个包含国家和代码的 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

【问题讨论】:

  • 你为什么不做一个plist而不是xml。有说服方法可以转换成字典或数组。
  • @InderKumarRathore- 是的,制作带有国家代码的 plist 将是一项漫长的任务
  • Sakshi 只需使用查找和替换命令,只需 3 分钟即可将其更改为 plist。你知道 plist 只是一个 xaml 如果你使用数据文件作为 plist 而不是 xml 你会看到事情变得多么容易。顺便说一句,你可以下载你的plist from here
  • @InderKumarRathore-thnaks 这是我学会将 xml 文件转换为 .plist 的新东西

标签: iphone ios tbxml


【解决方案1】:

未测试,但

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

应该工作

【讨论】:

  • rootElemnt = [TBXML nextSiblingNamed:@"item" searchFromElement:rootElemnt];将始终返回 nil,item 不是 rootElemnt 初始值的兄弟
猜你喜欢
  • 2016-02-13
  • 1970-01-01
  • 2021-01-03
  • 1970-01-01
  • 2020-01-26
  • 1970-01-01
  • 2019-07-16
  • 1970-01-01
  • 2016-06-17
相关资源
最近更新 更多