Questions can have more than one answer. Answers can lead to another question. When the Answer's NextQuestionId="0" then there will be no more questions nested underneath.
Questions and Answers have the following attributes:
I think I need to create a class (QuestionAndAnswers) to model Questions which contains a list Answers, but then the Answers could then contain another QuestionAndAnswers class. I need to loop through infinite levels i.e. without having something like the following in the code.
For each
For each
For each
Any thoughts would be greatly appreciated. I am not sure if I am over complicating things or whether I could do the same with simple Do...While or for each loops.
cmsesan1
Member
469 Points
188 Posts
Looping through nested XML
Apr 26, 2012 11:06 AM|LINK
I have some XML like this
Question Answer Question Answer Question Answer NextQuestionId="0" Answer Question Answer Answer Question Answer Question Answer Question Answerand am not sure how to loop through it.
Questions can have more than one answer. Answers can lead to another question. When the Answer's NextQuestionId="0" then there will be no more questions nested underneath.
Questions and Answers have the following attributes:
Question QuestionId, ParentQuestionId
Answer AnswerId, NextQuestionId
I think I need to create a class (QuestionAndAnswers) to model Questions which contains a list Answers, but then the Answers could then contain another QuestionAndAnswers class. I need to loop through infinite levels i.e. without having something like the following in the code.
For each
For each
For each
Any thoughts would be greatly appreciated. I am not sure if I am over complicating things or whether I could do the same with simple Do...While or for each loops.
Here is what I have so far but I am confused!
//Loop through rules and answers //bool blnNest = false; XElement xRules = xeSessionData.Element("Rules"); foreach (var xBaseRule in xRules.Nodes().OfType<XElement>().Where(x => x.Name == "Rule")) { //blnNest = false; int intRuleId = Convert.ToInt32(xBaseRule.Attribute("Id").Value); objValue.AuraSessionRules.Add(new SessionRules() { RuleId = intRuleId }); foreach (var xAnswer in xBaseRule.Nodes().OfType<XElement>().Where(x => x.Name == "Answer")) { objValue.AuraSessionAnswers.Add(new SessionAnswers() { RuleId = intRuleId, AnswerId = Convert.ToInt32(xAnswer.Attribute("Id").Value) }); } //do //{ // blnNest = true; //} while (blnNest == false); }Thank you very very very much for any help.
Ed