2013-03-21 88 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