我有以下从 XML 解析器中提取的字典。使用 github 库解析以下链接中的 XML 文件。
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.
}
他们认为没有任何值(value)正在返回。实际上,我在该 xml 中有 10 个元素,在解析过程中它显示我有 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 中。当用户按下按钮时,它应该转向新的 Controller 并显示答案是否正确,并在单击 ResultViewController 中的“继续”按钮后返回到 QuizViewController。现在我已经完成了所有这些设置。
现在想在 ResultViewController 中显示答案是否正确。
最佳答案
用这一行
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.
}
关于ios - 检索 NSDictionary 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15541796/