2013-03-21 114 views
0

我有下面这个从XML解析器中提取的字典。使用github库从以下链接解析XML文件。检索NSDictionary对象

XML to NSDictionary Parser Library

Quiz = { 
questions = (
    { 
    "@id" = 1; 
    answer = D; 
    A = "Under the rock"; 
    B = "Trees"; 
    C = "Mountain"; 
    D = Water; 
    question = "Where does the fish live?"; 
    }, 
    { 
    "@id" = 2; 
    answer = D; 
    A = "Four"; 
    B = "Two"; 
    C = "Six"; 
    D = Three; 
    question = "How many legs for a rabbit?"; 
    },...... 
    }; 

我试图获取关键的问题,答案,选择1-4的对象。但一些我不能通过价值。

for (NSString * key in xmlDictionary) { 
     NSDictionary * subDict = [xmlDictionary objectForKey:@"questions"]; 
     NSLog(@"Correct Answers \n\n%@", [subDict objectForKey:@"answer"]); 
     // all your other code here. 
    } 

不认为任何值返回。实际上,我有10个元素在该XML内,并在解析过程中显示,我有10个计数。但是,当我尝试计数xmlDictionary,它返回1.不知道这里发生了什么问题?

另外我将如何提取所有值取决于@id?

困惑!!!

更新:我改变了...标签... XML文件

NSDictionary *currentObject; 
    if (rowIndex < countXML) 
    { 
     currentObject=[muteArr objectAtIndex:rowIndex]; 
    } 
    else 
    { 
     [self performSegueWithIdentifier:@"simple" sender:self]; 
    } 

    NSString *questionLbl = [currentObject objectForKey:@"question"]; 
    NSString *op1Lbl = [currentObject objectForKey:@"A"]; 
    NSString *op2Lbl = [currentObject objectForKey:@"B"]; 
    NSString *op3Lbl = [currentObject objectForKey:@"C"]; 
    NSString *op4Lbl = [currentObject objectForKey:@"D"]; 
    NSString *answer = [currentObject objectForKey:@"answer"]; 
    NSString *questNoLbl = [currentObject objectForKey:@"@ID"]; 

questionID.text = [@"Question # " stringByAppendingString:questNoLbl]; 
    question.text = questionLbl; 

    [answer1 setTitle:op1Lbl forState:UIControlStateNormal]; 
    [answer2 setTitle:op2Lbl forState:UIControlStateNormal]; 
    [answer3 setTitle:op3Lbl forState:UIControlStateNormal]; 
    [answer4 setTitle:op4Lbl forState:UIControlStateNormal]; 

在现在,我有这样的代码来检索每个问题,并在QuizViewController显示的方式。当用户按下按钮时,它应该继续到新控制器,并显示答案是否正确,并在单击ResultViewController中的“继续”按钮后返回到QuizViewController。现在我有了所有这些设置。

现在想要显示ResultViewController中的答案是否正确。

回答

1

这一行

NSDictionary * subDict = [xmlDictionary objectForKey:@"questions"]; 

你得到相同的单词背,你已经离开。

试试这个:

for (NSString * key in xmlDictionary) { 
    NSDictionary * subDict = [xmlDictionary objectForKey:key]; 
    NSLog(@"Correct Answers \n\n%@", [subDict objectForKey:@"answer"]); 
    // all your other code here. 
} 

与您编辑的XML结构,你应该这样做:

NSDictionary * rootDict = [xmlDictionary objectForKey:@"questions"]; 
for (NSString * key in rootDict) { 
     NSDictionary * subDict = [rootDict objectForKey:key]; 
     NSLog(@"Correct Answers \n\n%@", [subDict objectForKey:@"answer"]); 
     // all your other code here. 
    } 
+0

正确答案。 – CroiOS 2013-03-21 07:44:26

+0

那么我得到(null)?也不明白为什么它返回1的“问题”。我猜想它会在“测验”中返回1个“问题”。任何想法如何解决它? – tmariaz 2013-03-21 08:28:23

+0

所以我的字典结构就像Quiz {questions({data 1},{data 2},...)};所以我想提取所有与上面显示的字典有关的数据值。 – tmariaz 2013-03-21 09:13:03